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;

Dart regular expressions have the same syntax and semantics as JavaScript regular expressions.

If you are using RegExp in JavaScript, then a word boundary would actually be represented by \\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.