Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading