正则表达式:如何匹配语法
REGEX: how to match the syntax ?
我在简单的正则表达式中有一个错误。我一直在尝试使用 std::regex
编写一些简单的正则表达式C++。这是我到目前为止的代码。
#include <iostream>
#include <regex>
#include <string>
int main(void)
{
std::string str = "Hello world";
std::regex rx("w+sw+"), rx2("ello");
std::cout << std::boolalpha << std::regex_match(str.begin(), str.end(), rx) << "n";
std::cout << std::boolalpha << std::regex_search(str.begin(), str.end(), rx2) << "n";
return 0;
}
该程序应打印(根据教程)
true
true
但它打印
false
false
我哪里犯了错误?提前谢谢。
注意:如果有帮助,我正在使用g++ -std=c++0x %file.cpp% -o %file%
如前所述,g++(GCC)没有正则表达式的正确实现(它未实现但仍可编译)。
Boost 库有一个正则表达式的实现,几乎与 C++11 中的正则表达式完全兼容。你可以用最少的代码更改来使用它(只需使用 boost:: 而不是 std::)。
下面是一个可以编译和工作的代码:
#include <iostream>
#include <boost/regex.hpp>
#include <string>
int main(void)
{
std::string str = "Hello world";
boost::regex rx("\w+\s\w+"), rx2("ello");
std::cout << std::boolalpha << boost::regex_match(str.begin(), str.end(), rx) << "n";
std::cout << std::boolalpha << boost::regex_search(str.begin(), str.end(), rx2) << "n";
return 0;
}
请注意,我还修复了 rx 反斜杠的缺失转义,因为没有它它就无法工作。
要编译它,你必须安装 libboost-regex-dev 包(如果不使用 Ubuntu/Debian,则安装类似的东西)并执行以下命令:
g++ -std=c++0x main.cpp -lboost_regex -o test
相关文章:
- 1d 智能指针不适用于语法 (*)++
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 基于ELO的团队匹配算法
- 没有用于初始化C++中的变量模板的匹配构造函数
- 调用'begin(int [n])'没有匹配函数
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 将模板与类模板扣除占位符参数匹配
- RE2 语法:如果不共享相同的前缀,则跳过匹配
- 为什么 'n boost::spirit 将 foo123 与 (+alpha | +alnum) 语法匹配?
- 正则表达式:如何匹配语法
- 在 Qi 中使用 Boost Phoenix 在语法中引用以前的匹配项
- 增强精神语法匹配噪声输入
- C++ 语法和编译器错误 - 运算符不匹配<<
- 将Boost.Proto语法与类型匹配
- 错误 C3867 "数据库::是用户和通行证匹配":非标准语法;使用 '&' 创建指向 Membe 的指针
- QSerialPort 新信号槽语法 没有匹配的成员函数,用于调用"连接"