使用正则表达式时,是否可以检查字符串中是否找不到数字?
所以,如果我这样做:
String temp;
String myText = "abcd";
temp = Regex.Match(myText, @"\d+").Value;
如何检查没有找到数字?
我是这么做的:
if (temp = ""){
//code
}
答案 0 :(得分:3)
更好的方法是
if (Regex.IsMatch(stringToCheck, @"\d+"){
// string has number
}
如果你想处理没有找到的数字,那么试试
if (!Regex.IsMatch(stringToCheck, @"\d+"){
// no numbers found
}
查找字符串中数字的所有匹配
MatchCollection matches = Regex.Matchs(stringToCheck, @"\d+");
foreach(Match match in matches){
//Console.WriteLine(match.Value);
}
答案 1 :(得分:1)
你没有得到匹配。如果你有匹配,你会在某个地方找到一个数字。
答案 2 :(得分:1)
只需与正则表达式进行反向匹配。
if ( !Regex.Match ( stringToCheck, "^[0-9]+$" ).Success ) {
}
答案 3 :(得分:1)
您可以使用IsMatch
,然后否定
if(!Regex.IsMatch(inp,".*\d.*"))//no number found
答案 4 :(得分:0)
Match temp;
String myText = "[0123456789]";
temp = Regex.Match(myText).Value;
bool NoDigits = !temp.Success;
对不起我的回答中的原始混淆。此外,你可以继续使用\ d标志,我只是喜欢[0123456789]因为它在这种简单的情况下使它更突出。
答案 5 :(得分:0)
String myText = "abcd";
if (Regex.IsMatch(myText, "[0-9]+"))
{
// there was a number
} else {
// no numbers
}