Regular Expression Generation for AngularJS ng-pattern

81 Views Asked by At

I'm using a regex to validate a form input. So basically a user can input "SELECT some_name of select_match".

So far I have the regex: \bSELECT\b \bof select_match\b The last part is the middle part, which I think should be [a-zA-Z] but I'm not sure how to place it in the middle. I've read multiple pages but can't get it to work.

Also preferably I'd like the regex to ignore spaces between "SELECT" and of "select_match". Meaning that SELECT blabla of select_match and SELECT blabla of select_match would both be validated as correct.

Can anyone tell me how to do this? Thank you.

1

There are 1 best solutions below

0
On BEST ANSWER

If I understood you correctly, this should work:

/^SELECT\s+(\w+)\s+of select_match$/

Notes:

  • This allows any number of spaces between "SELECT" and the match_name; and between the match_name and the "of" (but, at least 1. To change to at least 0, change the \s+ to a \s*)
  • After that, the rest of the string must be exactly like that (same spaces and words exactly).
  • The match_name will be in match group 1.

If this doesn't work, show a bit of your code (where you use it) and we can try to find the problem.

Note: If you are using it in ng-pattern lose the "/"s (being the pattern: ^SELECT\s+(\w+)\s+of select_match$).

Note2: If you are using it in a string, remember you might need to escape every "\" (making it a "\", and the result: ^SELECT\\s+(\\w+)\\s+of select_match$