Dart Regex for matching number or certain characters at the end of String

I'm trying to check for either numbers, 'e', 'π' or ' ' at the end of a String.

This is what I'm using: \s|[0-9]|e|π$. This is the code:

final regex = RegExp(r'\s|[0-9]|e|π$');

if (regex.hasMatch(_expression)) {  //_expression is the string
    //body
}

This always returns true. What's the error here?


Solution 1:

The $ at the end of the regex only binds to the pattern π. All other variants, therefore, will match regardless of whether the pattern is at the end of the string or not.

Ways to fix this would be either via a non-capturing group: (?:\s|[0-9]|e|π)$.

Or even simpler via a character class [\s0-9eπ]$.

I wrote a small program showing all three regexes in action:

https://dartpad.dev/c99c32251d9b8b5a12bcf5db231a47d9

Solution 2:

Try with the following regular expression:

void main() {
  final regex = RegExp(r'(\s|[0-9]|e|π)$');

  print(regex.hasMatch('959**')); // false
  print(regex.hasMatch('959')); // true
}

Solution 3:

Use the regex expression

\s$|[0-9]$|e$|π$

Should work