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:
Here is the walidation taking place:
As you can see string a12
does not match but it should...
"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.
What about:
(\w)+
It will returns all words
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.
精彩评论