Dart RegEx is not splitting String

Viewed 63

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

1 Answers

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
Related