结合这两个正则表达式为一体 [英] Combining these two Regular Expressions into one
本文介绍了结合这两个正则表达式为一体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的在C#如下:
公共静态布尔IsAlphaAndNumeric(字符串s)
{
返回Regex.IsMatch(S,@[A-ZA-Z] +)
和;&安培; Regex.IsMatch(S,@\d +);
}
我要检查,如果参数取值
至少包含一个字母字符和一个数字,我写了上面的方法来做到这一点。
但是,有没有办法我可以结合两个正则表达式([A-ZA-Z] +
和\d +
)合并为一个?
解决方案
@^(?=。* [A-ZA -Z])(?=。* \d)
^#从字符串
的开头(?=。* [A-ZA-Z])#期待对于后面有一个字母任意数目的字符,不提前指针
(?=。* \d)#期待任何数量的字符后跟数字)的
使用两个积极向前看符号的以保证它找到一个字母,之前的强校一个数字。您添加 ^
来只尝试期待一次,从字符串的开始。否则,正则表达式引擎将尝试匹配的字符串中的每一个点。
I have the following in C#:
public static bool IsAlphaAndNumeric(string s)
{
return Regex.IsMatch(s, @"[a-zA-Z]+")
&& Regex.IsMatch(s, @"\d+");
}
I want to check if parameter s
contains at least one alphabetical character and one digit and I wrote the above method to do so.
But is there a way I can combine the two regular expressions ("[a-zA-Z]+"
and "\d+"
) into one ?
解决方案
@"^(?=.*[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)
Uses two positive lookaheads to ensure it finds one letter, and one number before succeding. You add the ^
to only try looking forward once, from the start of the string. Otherwise, the regexp engine would try to match at every point in the string.
这篇关于结合这两个正则表达式为一体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文