我在C#中有以下内容:
public static bool IsAlphaAndNumeric(string s)
{
return Regex.IsMatch(s, @"[a-zA-Z]+")
&& Regex.IsMatch(s, @"\d+");
}
Run Code Online (Sandbox Code Playgroud)
我想检查参数是否s包含至少一个字母字符和一个数字,我写了上面的方法来做到这一点.
但有没有办法可以将两个正则表达式("[a-zA-Z]+"和"\d+")组合成一个?
Kob*_*obi 14
对于带有LINQ的C#:
return s.Any(Char.IsDigit) && s.Any(Char.IsLetter);
Run Code Online (Sandbox Code Playgroud)
gna*_*arf 11
@"^(?=.*[a-zA-Z])(?=.*\d)"
^ # From the begining of the string
(?=.*[a-zA-Z]) # look forward for any number of chars followed by a letter, don't advance pointer
(?=.*\d) # look forward for any number of chars followed by a digit)
Run Code Online (Sandbox Code Playgroud)
使用两个正向前瞻以确保它找到一个字母,并在成功之前找到一个数字.您^只需从字符串的开头添加一次尝试向前看一次.否则,regexp引擎会尝试匹配字符串中的每个点.
| 归档时间: |
|
| 查看次数: |
14957 次 |
| 最近记录: |