Using a regex capture directly in expression in C++

I'm trying to use a captured group directly in the regex. However, when I try to do this the program hangs indefinitely.

For example:

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

If I add another slash to the capture "<([a-zA-Z]+)>[az]</1>" , the program compiles but throws a "regex_error(regex_constants::error_backref)" exception.

Notes:
Compiler: Apple LLVM 5.1
I am using this as part of the process to clean junk from blocks of text. The document is not necessarily HTML/XML and desired text is not always within tags. So if possible, I would like to be able to do this with regular expressions, not a parser.


The backslash character in string literals is an escape character.

Either escape it "<([a-zA-Z]+)>[az]+</1>" or use a raw literal, R"(<([a-zA-Z]+)>[az]+</1>)"

With that, your program works as you would expect:

#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";
}

demo: http://coliru.stacked-crooked.com/a/ae20b09d46f975e9

The exception you're getting with 1 suggests that your compiler is configured to use GNU libstdc++, where regex was not implemented. Look up how to set it up to use LLVM libc++ or use boost.regex.

链接地址: http://www.djcxy.com/p/74816.html

上一篇: 使用Delphi的TRegex获取与哪个捕获组匹配的结果

下一篇: 直接在C ++表达式中使用正则表达式捕获