.NET的正则表达式字母和空格 [英] .NET RegEx for letters and spaces

查看:195
本文介绍了.NET的正则表达式字母和空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个普通的前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.

这篇关于.NET的正则表达式字母和空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆