Rasto
Rasto

Reputation: 17844

Regular expression for C# that matches all strings that has one or more word characters

Solved

(see comments)


The title says everything...

I thought I can write RE (have done really complicated ones in Java or on the paper). Now I cannot write this simple one that I need to validate user names in ASP.NET MVC model attribute. I would say that "\\.*\\w\\.*" should work according to resources that I've found. But it does not...


EDIT:

Here is what I have in my model code:

enter image description here


Here is the walidation taking place: enter image description here

As you can see string a12 does not match but it should...

Upvotes: 1

Views: 1650

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113342

"Word" in the context of regular expressions means non-whitespace, so new Regex(@"\w") is what you want in that case as e.g. new Regex(@"\w").IsMatch(" 1 ") returns true.

In a comment you say that you want letters to be matched, which wants new Regex(@"[\p{L}]") as new Regex(@"[\p{L}]").IsMatch(" a ") returns true but new Regex(@"[\p{L}]").IsMatch(" 1 ") returns false.

You can be more specific, treating this as new Regex(@"[\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}]") which looks for lowercase, uppercase, titlecase, modifier and other letters specifically, in case one of those categories isn't wished for. E.g. to not consider modifier letters to be "word characters" you would use new Regex(@"[\p{Ll}\p{Lu}\p{Lt}\p{Lo}]")

If the regex has to match the entire expression then one like .*\p{L}.* would do the trick.

If you need it to only match word characters (banning all other characters) then you want new Regex(@"^[\p{L}]+$") which means: start of expression, one or more letters, end of expression.

Upvotes: 2

cordellcp3
cordellcp3

Reputation: 3623

try your RegEx like the following:

String data = "drasto";

Regex regex  = new Regex(".*\\w.*");

var coll = regex.Matches(data);

foreach(var match in coll)
{
    Debug.Writeline(match.ToString());
}

This should work for your purpose.

Upvotes: 0

J4N
J4N

Reputation: 20761

What about:

(\w)+

It will returns all words

Upvotes: 1

Related Questions