0

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;
}
2
  • 1
    Something like [^']*'[^']*'[^']*'[^']*'[^']*'[^']*', plus capture groups in the appropriate places? Commented Feb 22, 2014 at 21:37
  • (.*)'(.*)'(.*)'(.*)'.*'(.*)' matches your requirement on regexpal.com, std::regex might behave differently. Commented Feb 22, 2014 at 21:43

2 Answers 2

3

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

you can test your code on Coliru using clang and libc++, like this: coliru.stacked-crooked.com/a/f0b5fd383bc227fc
@pepper_chico: Thanks for the tip. I'm not an expert with C++, but I suppose that Coliru doesn't have all the libraries available. But thanks anyway, since I don't imagine that an online tool exists for compiled languages. Julia Roberts is 46 year old and always pretty, how it is possible? This is my futur (and first) question on SO.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.