Home > Software engineering >  Dart RegEx is not splitting String
Dart RegEx is not splitting String

Time:01-25

Im a fresher to RegEx. I want to get all Syllables out of my String using this RegEx: /[^aeiouy]*[aeiouy] (?:[^aeiouy]*\$|[^aeiouy](?=[^aeiouy]))?/gi

And I implemented it in Dart like this:

void main() {
  String test = 'hairspray';
  final RegExp syllableRegex = RegExp("/[^aeiouy]*[aeiouy] (?:[^aeiouy]*\$|[^aeiouy](?=[^aeiouy]))?/gi");
  print(test.split(syllableRegex));
}

The Problem: Im getting the the word in the List not being splitted. What do I need to change to get the Words divided as List.

I tested the RegEx on regex101 and it shows up to Matches. But when Im using it in Dart with firstMatch I get null

CodePudding user response:

You need to

  • Use a mere string pattern without regex delimiters in Dart as a regex pattern
  • Flags are not used, i is implemented as a caseSensitive option to RegExp and g is implemented as a RegExp#allMatches method
  • You need to match and extract, not split with your pattern.

You can use

String test = 'hairspray';
final RegExp syllableRegex = RegExp(r"[^aeiouy]*[aeiouy] (?:[^aeiouy]*\$|[^aeiouy](?=[^aeiouy]))?",
                caseSensitive: true);
for (Match match in syllableRegex.allMatches(test)) {
   print(match.group(0));
}

Output:

hair
spray
  •  Tags:  
  • Related