Reputation: 39
I am trying to search and split a string based on regex. Suppose I have a string named var which looks like
| | | |-DeclRefExpr 0x5d91218 <col:5> 'int' lvalue Var 0x5d91120 'y' 'int'
Now I would like to split this into
| | | |-DeclRefExpr 0x5d91218 <col:5>
int
lvalue Var 0x5d91120
y
int
I know that the regex will be something like [^']* but I cant figure out how I can do it. What I have tried so far is:
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <regex>
using namespace std;
int main(){
std::string var = " | | | |-DeclRefExpr 0x5d91218 <col:5> 'int' lvalue Var 0x5d91120 'y' 'int'";
std::regex rgx("[^']*");
std::smatch match;
if (std::regex_search(var.begin(), var.end(), match, rgx)){
cout << match[3] << endl;
}
return 0;
}
Upvotes: 0
Views: 3183
Reputation: 50717
Besides @CasimiretHippolyte's method, you can also use regex_search()
:
const regex r("(.*)'(.*)'(.*)'(.*)'(.*)'(.*)'");
smatch sm;
if (regex_search(var, sm, r))
{
for (int i=1; i<sm.size(); i++)
{
cout << sm[i] << endl;
}
}
See it live: http://coliru.stacked-crooked.com/a/494ab2e0f1c5d420
Upvotes: 0
Reputation: 89639
Sorry I can't test this code, but it can perhaps work.
std::string var = "| | | |-DeclRefExpr 0x5d91218 <col:5> 'int' lvalue Var 0x5d91120 'y' 'int'";
std::regex wsaq_re("\\s*'|'+\\s*(?!')");
std::copy( std::sregex_token_iterator(var.begin(), var.end(), wsaq_re, -1),
std::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
Upvotes: 3