C++ std::正则表达式未按预期匹配
c++ std::regex doesn't match as expected
我试图实现一个简单的字符串测试方法使用c++ std::regex,在MS vc++ 2012。
const std::string str = "1.0.0.0029.443";
if ( std::regex_match( str, std::regex( "\.0\d+" ) ) )
std::cout << "matched." << std::endl;
我猜代码会匹配"。但是,它根本不匹配。
使用std::regex_search
来返回子匹配。
const std::string str = "1.0.0.0029.443";
std::regex rgx("(\.0[0-9]+)");
std::smatch match;
if (std::regex_search(str.begin(), str.end(), match, rgx)) {
std::cout << match[1] << 'n';
}
std::regex_match
报告精确匹配,即整个输入字符串必须匹配正则表达式。
匹配子序列,使用std::regex_search
为了确保您的regex匹配完整字符串,您需要这样做:
^(?:d+.)*d+$
翻译成
if ( std::regex_match( str, std::regex( "^(?:\d+\.)*\d+$" ) ) )
std::cout << "matched." << std::endl;
需要锚^
和$
的开头和结尾,否则您可能会在BANANA_0.1.12AND_APPLE
中间匹配字符串
相关文章:
- 如何使 std::正则表达式匹配 Utf8
- C++11 (MSVS2012) 正则表达式在多行 std::string 中查找文件名
- std::正则表达式捕获组语法错误
- std::正则表达式转义"+"符号
- 使用 STD 正则表达式标记逗号分隔的列表
- 对 std::string 执行正则表达式搜索和替换
- 仅查找第一个 std::正则表达式有效匹配
- 减少 std::正则表达式编译时间 C++
- 将Javascript正则表达式模式转换为C++std::regex的规则
- C++ std::正则表达式多行语法
- std::正则表达式无法按预期工作
- C++ - 在长时间的多行匹配期间,STD 正则表达式在 MSVC 中崩溃
- C++ std::正则表达式 查找多个匹配项
- 使用 std::正则表达式进行简单的 RX 是一种很好的做法
- c++中的STD正则表达式
- 如何使用正则表达式删除std::wstring中特定短语的所有实例
- Microsoft 的 std::正则表达式的实现
- C++ 2011 std::正则表达式根本不起作用
- 将正则表达式存储在变量(std::string)中
- c++ STD正则表达式问号问题