在C++中的表达式中直接使用正则表达式捕获
Using a regex capture directly in expression in C++
我正试图在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.
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- C++:正则表达式匹配代码,打印多个匹配项?