Search code examples
regexcase-insensitivedart

Why is this regexp not returning any matches?


I'm using a dart regular expression and trying to find a match.

Dart code: http://try.dartlang.org/s/SY1B

  RegExp exp = const RegExp("/my/i");
  String str = "Parse my string"; 
  Iterable<Match> matches = exp.allMatches(str);
  for (Match m in matches) {
    String match = m.group(0);
    print(match);
  }

I'm trying to perform a case-insensitive search to find all matches of a string. It says there are no matches. I'm sure I'm messing up somewhere because I'm new to regexp. How can I modify the code to find the match?

For context, I plan to modify the code to search for any string which I think will be achieved with the following code.

RegExp exp = const RegExp("/${searchTerm}/i");

Solution

  • The /pattern/flags syntax works in JavaScript, but not Dart as Dart doesn't have regex literals. Instead the docs show this:

    const RegExp(String pattern, [bool multiLine, bool ignoreCase])
    

    So your constructor should look like:

    RegExp exp = const RegExp("my", ignoreCase: true);