33

I am trying to create a regular expression pattern in C#. The pattern can only allow for:

  • letters
  • numbers
  • underscores

So far I am having little luck (i'm not good at RegEx). Here is what I have tried thus far:

// Create the regular expression
string pattern = @"\w+_";
Regex regex = new Regex(pattern);

// Compare a string against the regular expression
return regex.IsMatch(stringToTest);
Brad Mace
  • 26,397
  • 17
  • 98
  • 144
user70192
  • 13,048
  • 47
  • 156
  • 233

4 Answers4

46

EDIT :

@"^[a-zA-Z0-9\_]+$"

or

@"^\w+$"
Tolgahan Albayrak
  • 3,019
  • 1
  • 24
  • 27
  • 1
    @JoeWhite the second match also the uppercase english letters http://regexstorm.net/tester?p=%5e%5cw%2b%24&i=ABC&o=m – ihebiheb May 16 '16 at 09:40
29

@"^\w+$"

\w matches any "word character", defined as digits, letters, and underscores. It's Unicode-aware so it'll match letters with umlauts and such (better than trying to roll your own character class like [A-Za-z0-9_] which would only match English letters).

The ^ at the beginning means "match the beginning of the string here", and the $ at the end means "match the end of the string here". Without those, e.g. if you just had @"\w+", then "@@Foo@@" would match, because it contains one or more word characters. With the ^ and $, then "@@Foo@@" would not match (which sounds like what you're looking for), because you don't have beginning-of-string followed by one-or-more-word-characters followed by end-of-string.

Joe White
  • 91,162
  • 55
  • 215
  • 326
3

Try experimenting with something like http://www.weitz.de/regex-coach/ which lets you develop regex interactively.

It's designed for Perl, but helped me understand how a regex works in practice.

Byron Ross
  • 1,535
  • 1
  • 15
  • 21
-1

Regex

packedasciiRegex = new Regex(@"^[!#$%&'()*+,-./:;?@[\]^_]*$");
Mike Szyndel
  • 10,124
  • 7
  • 44
  • 61
Krushik
  • 87
  • 1
  • 1