regex check for white space in middle of string

2019-01-24 04:33发布

I want to validate that the characters are alpha numeric:

Regex aNum = Regex("[a-z][A-Z][0-9]");

I want to add the option that there might be a white space, so it would be a two word expression:

Regex aNum = Regex("[a-z][A-Z][0-9]["\\s]");

but couldn't find the correct syntax.

id applicate any incite.

4条回答
相关推荐>>
2楼-- · 2019-01-24 04:57

To not allow empty strings then

Regex.IsMatch(s ?? "",@"^[\w\s]+$"); 

and to allow empty strings

Regex.IsMatch(s ?? "",@"^[\w\s]*$"); 

I added the ?? "" as IsMatch does not accept null arguments

查看更多
看我几分像从前
3楼-- · 2019-01-24 05:07

[A-Za-z0-9\s]{1,} should work for you. It matches any string which contains alphanumeric or whitespace characters and is at least one char long. If you accept underscores, too you shorten it to [\w\s]{1,}.

You should add ^ and $ to verify the whole string matches and not only a part of the string:

^[A-Za-z0-9\s]{1,}$ or ^[\w\s]{1,}$.

查看更多
在下西门庆
4楼-- · 2019-01-24 05:11

Exactly two words with single space:

Regex aNum = Regex("[a-zA-Z0-9]+[\s][a-zA-Z0-9]+");

OR any number of words having any number of spaces:

Regex aNum = Regex("[a-zA-Z0-9\s]");
查看更多
We Are One
5楼-- · 2019-01-24 05:12
"[A-Za-z0-9\s]*"

matches alphanumeric characters and whitespace. If you want a word that can contain whitespace but want to ensure it starts and ends with an alphanumeric character you could try

"[A-Za-z0-9][A-Za-z0-9\s]*[A-Za-z0-9]|[A-Za-z0-9]"
查看更多
登录 后发表回答