6

Basically, I want to count sets of specific characters in a string. In other words I need to count all Letters and Numbers, and nothing else. But I cant seem to find the right (regex) syntax. Here's what i have ...

public double AlphaNumericCount(string s)
{
    double count = Regex.Matches(s, "[A-Z].[a-z].[0-9]").Count;
        return count;
}

I've been looking around, but cant seem to find anything that allows more than one set of characters. Again, I'm not sure on the syntax maybe it should be "[A-Z]/[a-z]/[0-9]" or something. Anywho, go easy on me - its my first day using Regex.

Thanks.

0

4 Answers 4

5

Regular Expression Cheat Sheet

Expresso Regular Expression tool

[A-Z].[a-z].[0-9] will match any capital letter ([A-Z]), followed by any character (.), followed by any lower case letter ([a-z]), followed by any character (.), followed by any number ([0-9]).

What you want to match on any letter or number is [A-Za-z0-9].

Sign up to request clarification or add additional context in comments.

Comments

4

If the use of regular expressions is not required, there is an easy, alternate solution:

return s.ToCharArray().Count(c => Char.IsNumber(c) || Char.IsLetter(c));

1 Comment

ToCharArray() is not necessary here. string already implements IEnumerable<char>
3

Try this one:

^[a-zA-Z0-9]+$

see: regexlib.com

Comments

3

If you want to avoid regular expressions, you can simply iterate through the characters in the string and check if they're a letter or digit using Char.IsLetterOrDigit.

public int AlphaNumericCount(string s)
{
    int count = 0;

    for(int i = 0; i < s.Length; i++)
    {
       if(Char.IsLetterOrDigit(s[i])) 
          count++;
    }

    return count;
}

1 Comment

No problem. Regex might look neater but, depending on the length of the string/number of calls, they may be slower.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.