Dart RegExp word boundary equivalent

957

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.

Share:
957
Ella Gogo
Author by

Ella Gogo

Updated on December 11, 2022

Comments

  • Ella Gogo
    Ella Gogo over 1 year

    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.

    Thanks.

  • Ella Gogo
    Ella Gogo almost 5 years
    Hi, I've seem the documentation, and searched how to write this regex in JavaScript. Unfortunately I didn't realize that I need to escape this. Thanks a lot.