4

I try to split a string with multiple delimiters (spaces and parenthesis), but all I managed to do is a split with one delimiter thanks to getline(...).

Here's an example of what I try to do:

hello world(12)

And I would like to get theses as strings:

hello
world
(
12
)

Any help?

Niall
  • 30,036
  • 10
  • 99
  • 142
Brighter
  • 67
  • 3

1 Answers1

3

You could simply do matching. Use the below regex and then append the matched results to a list if necessary.

[^()\s]+(?=[()])|[^\s()]+|[()]

Code:

Thanks to @Lightness

#include <regex>
#include <iostream>

int main()
{
    std::string s("hello world(12)");
    std::regex r("[^()\\s]+(?=[()])|[^\\s()]+|[()]");

    auto it  = std::sregex_iterator(s.begin(), s.end(), r);
    auto end = std::sregex_iterator();

    for ( ; it != end; ++it)
        std::cout << it->str() << '\n';
}

DEMO

Community
  • 1
  • 1
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274