具有至少一个字母的字母数字字符串或字符串中的至少一个数字的正则表达式

Arn*_*Das 5 c# regex

为了测试一个字母数字字符串,我们通常使用正则表达式"^[a-zA-Z0-9_]*$"(或最优选地"^\w+$"用于C#).但是这个正则表达式只接受数字字符串或仅字母表字符串,如"12345678""asdfgth".

我需要一个正则表达式,它只接受至少包含一个字母和一个数字的字母数字字符串.也就是说,正则表达式"ar56ji"将是正确的字符串之一,而不是之前说过的字符串.

提前致谢.

rid*_*ner 9

这应该这样做:

if (Regex.IsMatch(subjectString, @"
    # Match string having one letter and one digit (min).
    \A                        # Anchor to start of string.
      (?=[^0-9]*[0-9])        # at least one number and
      (?=[^A-Za-z]*[A-Za-z])  # at least one letter.
      \w+                     # Match string of alphanums.
    \Z                        # Anchor to end of string.
    ",
    RegexOptions.IgnorePatternWhitespace)) {
    // Successful match
} else {
    // Match attempt failed
} 
Run Code Online (Sandbox Code Playgroud)

编辑2012-08-28通过将懒角星改为特定的贪婪char类来提高前瞻效率.