I try to match words and sentences that include exactly word "world" in my flutter application. I think that the best way to do this it to use word boundaries. My regex looks like this:
String str = "world"; var regexp = RegExp("\b($str)\b", caseSensitive: false);
But it does not work. This is the output:
regexp.hasMatch("Hello World"); //false regexp.hasMatch("World"); //false regexp.hasMatch("worlds"); //false as expected
Does \b not work in Dart? Does anyone know how to achieve desired behavior? I can't find any information about this.
Solution 1: Tim Biegeleisen
From the Dart regex documentation;
If you are using
\\b, i.e. we need to add an extra escape to the
\b word boundary:
String str = "world"; var regexp = RegExp("\\b($str)\\b", caseSensitive: false); regexp.hasMatch("Hello World"); // true
Note that you should generally avoid using
RegExp if possible, and instead use regex literals. The reason for this is that literals relax and make the regex syntax simpler.