Home > Software design >  Put everything in ordered groups, but have chars in parentheses grouped together
Put everything in ordered groups, but have chars in parentheses grouped together

Time:04-19

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.

CodePudding user response:

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.

CodePudding user response:

If you want to group the string by identical characters, I would consider using a stack to keep a running storage of the congruent, consecutive characters. Once you reach a character that does not match, you can clear the entire stack until it is empty.

You can add more code (if statement logic) to keep populating a stack once an opening parentheses is read until a closing parentheses is read.

  • Related