在C++中的表达式中直接使用正则表达式捕获

Using a regex capture directly in expression in C++

本文关键字:正则表达式 C++ 表达式      更新时间:2023-10-16

我正试图在regex中直接使用捕获的组。然而,当我尝试这样做时,程序会无限期地挂起。

例如:

string input = "<Tag>blahblah</Tag>";
regex r1("<([a-zA-Z]+)>[a-z]+</1>");
string result = regex_replace(result, regex, "");

如果我在捕获"<([a-zA-Z]+)>[a-z]</\1>"中添加另一个斜杠,程序会编译,但会抛出"regex_error(regex_constants:error_backref)"异常。

注意:
编译器:Apple LLVM 5.1
我将此作为清除文本块中垃圾的过程的一部分。文档不一定是HTML/XML,所需的文本也不总是在标记中。因此,如果可能的话,我希望能够用正则表达式而不是解析器来实现这一点。

字符串文字中的反斜杠字符是转义字符。

对其进行转义"<([a-zA-Z]+)>[a-z]+</\1>"或使用原始文字R"(<([a-zA-Z]+)>[a-z]+</1>)"

有了它,你的程序就如你所期望的那样工作:

#include <regex>
#include <iostream>
int main()
{
    std::string input = "Hello<Tag>blahblah</Tag> World";
    std::regex r1("<([a-zA-Z]+)>[a-z]+</\1>");
    std::string result = regex_replace(input, r1, "");
    std::cout << "The result is '" << result << "'n";
}

演示:http://coliru.stacked-crooked.com/a/ae20b09d46f975e9

\1出现的异常表明,编译器已配置为使用GNU libstdc++,而regex并未在其中实现。查找如何将其设置为使用LLVM libc++或使用boost.regex.