flutter
flutter

Reputation: 6786

Escape quote in Dart Regex

I'm trying to use the regex /^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$/ with dart regex. I've seen you can use raw strings. So Ive put the above in between r'' like this:

r'^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$' but the ' is messing it up. How do I tell dart this is a special character..

EDIT

I tried this but it doesn't seem to work

static final RegExp _usernameRegExp = RegExp(
    r"^[a-zA-Z0-9_$&+:;=?@#|'<>.^*()%!-]+$",
  );

So I have a TextField with a text controller for a username. A method like this

static bool isValidUsername(String username) {
    return (_usernameRegExp.hasMatch(username));  
  }

I pass the controller.text as the username. I've a function:

bool get isUserNameValid => (Validators.isValidUsername(userNameTextController.text.trim()));

I can type all the given characters in to the textbook but not '

Upvotes: 0

Views: 2678

Answers (1)

lrn
lrn

Reputation: 71903

Your RegExp source contains ', so you can't use that as string delimiter without allowing escapes. It also contains $ so you want to avoid allowing escapes.

You can use " as delimiter instead, so a raw string like r"...".

However, Dart also has "multi-line strings" which are delimited by """ or '''. They can, but do not have to, contain newlines. You can use those for strings containing both ' and ". That allows r'''...'''.

And you can obviously also use escapes for all characters that mean something in a string literal.

So, for your code, that would be one of:

r'''^[\w&+:;=?@#|'<>.^*()%!-]+$'''
r"^[\w&+:;=?@#|'<>.^*()%!-]+$"
'^[\\w&+:;=?@#|\'<>.^*()%!-]+\$'

(I changed A-Za-z0-9$_ to \w, because that's precisely what \w means).

In practice, I'll always use a raw string for regexps. It's far too easy, and far too dangerous, to forget to escape a backslash, so use one of the first two options.

I'd probably escape the - too, making it [....\-] instead of relying on the position to make it non-significant in the character class. It's a fragile design that breaks if yo add one more character at the end of the character class, instead of adding it before the -. It's less fragile if you escape the -.

Upvotes: 5

Related Questions