.NET的正则表达式字母和空格空格、字母、正则表达式、NET

由网友(斩尽风花雪月)分享简介:我想创建一个普通的前pression在C#中,只允许字母数字字符和空格。目前,我正尝试以下操作:I am trying to create a regular expression in C# that allows only alphanumeric characters and spaces. Currently...

我想创建一个普通的前pression在C#中,只允许字母数字字符和空格。目前,我正尝试以下操作:

I am trying to create a regular expression in C# that allows only alphanumeric characters and spaces. Currently, I am trying the following:

string pattern = @"^w+$";
Regex regex = new Regex(pattern);
if (regex.IsMatch(value) == false)
{
  // Display error
}

我是什么做错了吗?

What am I doing wrong?

推荐答案

如果你只需要英语,试试这个正则表达式:

If you just need English, try this regex:

"^[0-9A-Za-z ]+$"

在括号指定的字符集

The brackets specify a set of characters

0-9 :所有数字

A-Z :所有的大写字母

A-Z :所有的小写字母

:空间

如果您需要单向code /国际化,你可以试试这个正则表达式:

If you need unicode / internationalization, you can try this regex:

"^[w ]+$"

这正则表达式匹配的所有单code字母和数字,这可能比你更需要的,所以如果你只需要英语,第一个正则表达式将会更简单,更快地执行。

This regex will match all unicode letters and numbers, which may be more than you need, so if you just need English, the first regex will be simpler and faster to execute.

请注意,无论对于正则表达式我已经包含了^和$运算符,它的意思是匹配的开始和结束。如果你需要拉了这一点,一个字符串,它并不需要是整个字符串,就可以删除这两个运营商。

Note that for both regex I have included the ^ and $ operator which mean match at start and end. If you need to pull this out of a string and it doesn't need to be the entire string, you can remove those two operators.

阅读全文

相关推荐

最新文章