简体   繁体   English

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

[英]C# Regular Expression to match letters, numbers and underscore

I am trying to create a regular expression pattern in C#. 我想在C#中创建一个正则表达式模式。 The pattern can only allow for: 该模式只允许:

  • letters
  • numbers 数字
  • underscores 下划线

So far I am having little luck (i'm not good at RegEx). 到目前为止我运气不好(我不擅长RegEx)。 Here is what I have tried thus far: 这是我到目前为止所尝试的:

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

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

EDIT : 编辑:

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

or 要么

@"^\w+$"

@"^\\w+$" @ “^ \\ w + $”

\\w matches any "word character", defined as digits, letters, and underscores. \\ w匹配任何“单词字符”,定义为数字,字母和下划线。 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). 它具有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, eg if you just had @"\\w+", then "@@Foo@@" would match, because it contains one or more word characters. 没有这些,例如,如果你只有@“\\ w +”,那么“@@ Foo @@”将匹配,因为它包含一个或多个单词字符。 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. 使用^和$,然后“@@ Foo @@”将不匹配(这听起来像你正在寻找的那样),因为你没有字符串的开头,后跟一个或多个字 - 字符串后跟字符串结尾。

Try experimenting with something like http://www.weitz.de/regex-coach/ which lets you develop regex interactively. 尝试使用像http://www.weitz.de/regex-coach/这样的东西,它可以让你以交互方式开发正则表达式。

It's designed for Perl, but helped me understand how a regex works in practice. 它是为Perl设计的,但帮助我了解正则表达式在实践中是如何工作的。

正则表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM