user70192
user70192

Reputation: 14204

C# Regular Expression to match letters, numbers and underscore

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

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);

Upvotes: 37

Views: 99725

Answers (4)

Krushik
Krushik

Reputation: 105

Regex

packedasciiRegex = new Regex(@"^[!#$%&'()*+,-./:;?@[\]^_]*$");

Upvotes: -2

Tolgahan Albayrak
Tolgahan Albayrak

Reputation: 3206

EDIT :

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

or

@"^\w+$"

Upvotes: 55

Joe White
Joe White

Reputation: 97676

@"^\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.

Upvotes: 33

Byron Ross
Byron Ross

Reputation: 1605

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.

Upvotes: 3

Related Questions