Reputation: 67
I have a tested regular expression to split ,
delimited phrases in a string, except where the ,
is in brackets.
Testing the regular expression with this string in https://regex101.com/r/COMj2b/1 with ECMAScript flavour gives desired matches. No matches are printed in my Dart version.
Any guidance much appreciated!
void main() {
String s = """Joe's Jazz Band (Ensemble), Fred Dagg (Guitar), Tommy Tucker (Horn, Clarinet), The Pied Piper (Whistle)""";
RegExp re = RegExp(r'([^,(]*\([^)]*\))*[^,]*(,|$)');
List li = s.split(re);
print('$li');
}
My Dart code prints [,,,]
.
I expected it to print:
['Joe's Jazz Band (Ensemble)', 'Fred Dagg (Guitar)', 'Tommy Tucker (Horn, Clarinet)', 'The Pied Piper (Whistle)']
Upvotes: 2
Views: 256
Reputation: 18923
split does not return the matches but splits the string at matches of pattern and returns a list of substrings.
Supposing that the separator is a )
bracket followed by zero or more spaces and a comma, this works with split:
void main() {
String s = """Joe's Jazz Band (Ensemble), Fred Dagg (Guitar), Tommy Tucker (Horn, Clarinet), The Pied Piper (Whistle)""";
RegExp re = RegExp(r'\)[ \t]*,');
Iterable li = s.split(re).map((item) => item.endsWith(")") ? item.trim() : "$item)".trim());
li.forEach((item) => print('$item'));
}
Note that it is necessary to add a )
at the last splitted element.
The trim()
is not necessary at less you want to remove leading and trailing whitespaces.
Upvotes: 1
Reputation: 3690
As said @attdona split doesn't return matches, so if you want to get matches, use something like that:
void main() {
String s = """Joe's Jazz Band (Ensemble), Fred Dagg (Guitar), Tommy Tucker (Horn, Clarinet), The Pied Piper (Whistle)""";
RegExp re = RegExp(r'([^,(]*\([^)]*\))*[^,]*(,|$)');
List l = re.allMatches(s).toList();
List<String> li = new List();
for(Match e in l) {
li.add(e.group(0));
}
print('$li');
}
Upvotes: 0