1

I want to split this expression

A+ + B

by the "+" in between so that I have A+ and B at the end

Note that the + after A is apart of the first token and I don't want to split it

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string/regex.hpp>
#include <vector>
using namespace std;

int main()
{
    string expression="A+ + B"; 
    vector <string> resultArray;
    boost::algorithm::split_regex( resultArray, expression,  boost::regex( " + " ));
    for (int i=0; i<resultArray.size();i++){
    cout <<resultArray[i]<< endl ;
    }
return 0;
}
1
  • yes the plus with space before and after it Commented Jan 17, 2014 at 14:44

2 Answers 2

1

+ is a regex character and you have to escape it. Not sure how it do in c++ but usually in other languages its done using a backslash(\) like this \+ and, for the space, you can use \s

So assume this will be your splitting regex:

\\s+\\+\\s+

It means: any number of spaces, then a plus, then any number of spaces.

Sign up to request clarification or add additional context in comments.

Comments

0

The + needs to be escaped with \, and furthermore the \ itself needs to be escaped with \ again because this is C++. So:

int main()
{
    string expression="A+ + B"; 
    vector <string> resultArray;
    boost::regex rx(" \\+ ");
    boost::algorithm::split_regex( resultArray, expression, rx);
    for (size_t i=0; i<resultArray.size();i++)
    {   
        cout << "[" << i << "] : " << resultArray[i]<< endl ;
    }   
return 0;
}

Output:

jdibling@hurricane:~/dev/hacks$ ./hacks 
[0] : A+
[1] : B

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.