c++ - 至少一个字符的正则表达式

标签 c++ regex boost

如何检查字符串是否至少包含一个字符?我想消除只有特殊字符的字符串,所以我决定最简单的方法是检查是否至少有一个字符或数字,所以我创建了 [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/

相关文章:

c++ - llvm/clang 自身重新编译

python - 使用正则表达式从 python 中的列表项中删除子字符串

c++ - 当我可以将 RNG 传递给分布时,为什么要使用 variate_generator? (特别是 C++ 和 Boost)

c++ - 如何使用 boost odeint 处理过去的时间偏移?

c++ - 如何通过 getter 函数序列化包含指针的类?

c++ - 自动化 C++ 类的 pimpl'ing——有简单的方法吗?

C++回调函数运行时错误

c++ - 使用共享变量的线程

java - 正则表达式返回不期望的结果

c# - 如何不包含正则表达式的一部分