escapeForRegex method

  1. @useResult
String escapeForRegex()

Escapes this string for use as a literal inside a RegExp.

Returns a new string with regex metacharacters backslash-escaped so that the resulting pattern matches this string literally. Uses a non-null fallback for each match so the result never contains the literal "null".

Example:

r'$10.00'.escapeForRegex();  // r'\$10\.00'
'a+b'.escapeForRegex();      // r'a\+b'

Implementation

@useResult
String escapeForRegex() {
  if (isEmpty) return this;
  return replaceAllMapped(
    _regexSpecialChars,
    (Match m) => '\\${m.group(0) ?? ''}',
  );
}