如何检查字符串是否至少包含一个字符?我想消除只有特殊字符的字符串,所以我决定最简单的方法是检查是否至少有一个字符或数字,所以我创建了 [a-zA-Z0-9] {1,}
和 [a-zA-Z0-9]+
但这些都不起作用。
boost::regex noSpecialCharacters("[a-zA-Z0-9]+");
boost::regex noSpecialCharacters2("[a-zA-Z0-9]{1,}");
string tab[SIZE] = {"father", "apple is red"};
for (int i = 0; i < SIZE; i++) {
if (!boost::regex_match(tab[i], noSpecialCharacters)) {
puts("This is it!");
} else {
puts("or not");
}
if (!boost::regex_match(tab[i], noSpecialCharacters2)) {
puts("This is it!");
} else {
puts("or not");
}
}
“apple is red”答案正确,但“father”不正确。
最佳答案
apple is red
将不匹配,因为根据 here (我的粗体):
Note that the result is true only if the expression matches the whole of the input sequence.
这意味着空格使其无效。然后它继续说(再次,我的粗体):
If you want to search for an expression somewhere within the sequence then use
regex_search
.
如果您要查找的只是其中某处的一个有效字符,您可以使用 regex_match()
和 ".*[a-zA-Z0-9].* “
或 regex_search()
与 [a-zA-Z0-9]”
。
关于c++ - 至少一个字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22061659/