Put everything in ordered groups, but have chars in parentheses grouped together

Advertisements

Say I have this string:

111 222 (333 444) 555 666 (777) 888

What I want is:
Group 1: 111 222
Group 2: 333 444
Group 3: 555 666
Group 4: 777
Group 5: 888

I have this regex \(([^\)]+)\) but it only captures what’s between parens.

>Solution :

You can use

String text = "111 222 (333 444) 555 666 (777) 888";
RegExp rx = new RegExp(r'\(([^()]+)\)|[^()]+');
var values = rx.allMatches(text).map((z) => z.group(1) != null ? z.group(1)?.trim() : z.group(0)?.trim()).toList();
print(values);
// => [111 222, 333 444, 555 666, 777, 888]

See the regex demo. The output is either trimmed Group 1 values, or the whole match values (also trimmed) otherwise. The \(([^()]+)\)|[^()]+ pattern matches a (, then captures into Group 1 any one or more chars other than parentheses and then matches a ), or matches one or more chars other than parentheses.

To avoid empty items, you may require at least one non-whitespace:

\(\s*([^\s()][^()]*)\)|[^\s()][^()]*

See this regex demo. Details:

  • \( – a ( char
  • \s* – zero or more whitespaces
  • ([^\s()][^()]*) – Group 1: a char other than whitespace, ( and ), and then zero or more chars other than round parentheses
  • \) – a ) char
  • | – or
  • [^\s()][^()]* – a char other than whitespace, ( and ), and then zero or more chars other than round parentheses.

Leave a ReplyCancel reply