Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only given captured group <regex> c++

Tags:

c++

regex

c++11

I want to extract tag's inner content. From the following string:

<tag1 val=123>Hello</tag1>

I just want to get

Hello

What I do:

string s = "<tag1 val=123>Hello</tag1>";
regex re("<tag1.*>(.*)</tag1>");
smatch matches;
bool b = regex_match(s, matches, re);

But it returns two matches:

<tag1 val=123>Hello</tag1>
Hello

And when I try to get only 1st captured group like this:

"<tag1.*>(.*)</tag1>\1"

I get zero matches.

Please, advise.

like image 216
Artem Avatar asked Oct 16 '25 18:10

Artem


1 Answers

The regex_match returns only a single match, with all the capturing group submatches (their number depends on how many groups there are in the pattern).

Here, you only get 1 match that contains two submatches: 1) whole match, 2) capture group 1 value.

To obtain the contents of the capturing group, you need to access the smatches object second element, matches[1].str() or matches.str(1)

Note that when you write "<tag1.*>(.*)</tag1>\1", the \1 is not parsed as a backreference, but as a char with octal code 1. Even if you defined a backreference (as "<tag1.*>(.*)</tag1>\\1") you would require the whole text captured with the capturing group 1 to be repeated after </tag1> - that is definitely not what you want. Actually, I doubt this regex is any good, at least, you need to replace ".*" with "[\\s\\S]*?", but it is still a fragile approach to parse HTML with regex.

like image 167
Wiktor Stribiżew Avatar answered Oct 18 '25 08:10

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!