C#正则表达式匹配字母、数字和下划线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/885860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 08:24:46  来源:igfitidea点击:

C# Regular Expression to match letters, numbers and underscore

c#regex

提问by user70192

I am trying to create a regular expression pattern in C#. The pattern can only allow for:

我正在尝试在 C# 中创建一个正则表达式模式。该模式只能允许:

  • letters
  • numbers
  • underscores
  • 字母
  • 数字
  • 下划线

So far I am having little luck (i'm not good at RegEx). Here is what I have tried thus far:

到目前为止,我运气不佳(我不擅长 RegEx)。这是我迄今为止尝试过的:

// Create the regular expression
string pattern = @"\w+_";
Regex regex = new Regex(pattern);

// Compare a string against the regular expression
return regex.IsMatch(stringToTest);

采纳答案by Tolgahan Albayrak

EDIT :

编辑 :

@"^[a-zA-Z0-9\_]+$"

or

或者

@"^\w+$"

回答by Byron Ross

Try experimenting with something like http://www.weitz.de/regex-coach/which lets you develop regex interactively.

It's designed for Perl, but helped me understand how a regex works in practice.

尝试尝试像http://www.weitz.de/regex-coach/这样的东西,它可以让你交互式地开发正则表达式。

它是为 Perl 设计的,但帮助我理解了正则表达式在实践中是如何工作的。

回答by Joe White

@"^\w+$"

@"^\w+$"

\w matches any "word character", defined as digits, letters, and underscores. It's Unicode-aware so it'll match letters with umlauts and such (better than trying to roll your own character class like [A-Za-z0-9_] which would only match English letters).

\w 匹配任何“单词字符”,定义为数字、字母和下划线。它是 Unicode 感知的,因此它会将字母与变音符号等匹配(比尝试滚动您自己的字符类更好,例如 [A-Za-z0-9_] 只匹配英文字母)。

The ^ at the beginning means "match the beginning of the string here", and the $ at the end means "match the end of the string here". Without those, e.g. if you just had @"\w+", then "@@Foo@@" would match, because it containsone or more word characters. With the ^ and $, then "@@Foo@@" would not match (which sounds like what you're looking for), because you don't have beginning-of-string followed by one-or-more-word-characters followed by end-of-string.

开头的 ^ 表示“匹配这里字符串的开头”,末尾的 $ 表示“匹配这里字符串的结尾”。没有这些,例如,如果您只有@"\w+",那么"@@Foo@@" 将匹配,因为它包含一个或多个单词字符。使用 ^ 和 $,则“@@Foo@@”将不匹配(这听起来像您要查找的内容),因为您没有字符串开头后跟一个或多个单词-字符后跟字符串结尾。

回答by Krushik

Regex

正则表达式

packedasciiRegex = new Regex(@"^[!#$%&'()*+,-./:;?@[\]^_]*$");