正则表达式:如何匹配语法

REGEX: how to match the syntax ?

本文关键字:语法 何匹配 正则表达式      更新时间:2023-10-16

我在简单的正则表达式中有一个错误。我一直在尝试使用 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