0

I am looking Regex formula for Dart, to check either the input is matching specific any string or not which I proved. Example: input is 'butter', and proved strings are ['but','burst','bus']. The program should return false because 'but' is not equal to the 'butter'. But it is returning true as below code.

void main() {
  const string = 'Can you give me a butter';
  const pattern = r'(but)|(burst)|(bus)';
  final regExp = RegExp(pattern);
  print(regExp.hasMatch(string.toLowerCase())); //true
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
Cihat Şaman
  • 3,674
  • 4
  • 14
  • 24
  • 1
    You don't need to add `$` for each possibility. Group them and add `$` at the end: `(but|burst|bus)$` – Abd Elbeltaji Aug 13 '21 at 08:02
  • 1
    Dart uses the same regular expression syntax as JavaScript. There's no reason why you can't use `$` in the Dart regular expression pattern as long as you use raw strings (prefixed with `r`), which you're already doing. – jamesdlin Aug 13 '21 at 08:05
  • But, a little looks different because it is not working like that ``const pattern = r'(but)$|(burst)$|(bus)$';`` But in Js it is working like that ``let testRegex=/(but)$|(burst)$|(bus)$/i`` – Cihat Şaman Aug 13 '21 at 08:09
  • 2
    BTW, `$` refers to `end of line` if you are expecting the word to be anywhere use `\b`: `\b(but|burst|bus)\b` – Abd Elbeltaji Aug 13 '21 at 08:10
  • @AbdElbeltaji I am looking at that actually but I couldn't it. ``/\b: \b(butter|burst|bus)\b/i`` I did like that but it is returns false . – Cihat Şaman Aug 13 '21 at 09:00
  • 1
    @CihatŞaman `/\b(but|burst|bus)\b/i` – Abd Elbeltaji Aug 13 '21 at 09:02
  • Totaly it is working well Thanks. – Cihat Şaman Aug 13 '21 at 09:09

1 Answers1

2

When I changed the codes as below it worked well.

void main() {
  const string = 'Can you give me a But asasa';
  const pattern = r'\b(but|burst|bus)\b';
  final regExp = RegExp(pattern, caseSensitive: false);
  print(regExp.hasMatch(string)); 
}
lrn
  • 64,680
  • 7
  • 105
  • 121
Cihat Şaman
  • 3,674
  • 4
  • 14
  • 24