Sahil
Sahil

Reputation: 1983

Extract matched strings in C++ with regex

I have following test strings.

#5=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);
#6=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);
#7=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);

I need to extract:

Can someone please suggest how I can achieve this in C++ with regex.

I tried following as simple example (it's a loop that processes one line at a time):

std::regex e ("\#[:d:]+");
if (std::regex_match(sLine,e)){
   //store it and process it
}

output should be:

#5

and

'xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$ ?? (not sure)

Upvotes: 0

Views: 225

Answers (1)

Ro Yo Mi
Ro Yo Mi

Reputation: 15000

Description

This expression will:

  • capture the initial # and integer
  • capture the value between the parentheses

^(\#\d+).*?\(([^)]*)\)

enter image description here

Example

Live Demo

Sample Text

#5=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);
#6=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);
#7=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$);

Capture Groups

Group 0 gets the entire matched string
Group 1 gets the # and integer
Group 2 gets the value between the parentheses

[0][0] = #5=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$)
[0][1] = #5
[0][2] = 'xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$

[1][0] = #6=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$)
[1][1] = #6
[1][2] = 'xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$

[2][0] = #7=BUILDING('xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$)
[2][1] = #7
[2][2] = 'xxxcdccx',#5,$,$,$,#21,$,$,.ELEMENT.,$,$,$

Upvotes: 1

Related Questions