Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  72] [ 4]  / answers: 1 / hits: 174849  / 13 Years ago, thu, june 9, 2011, 12:00:00

I'm new to Regex and I'm trying to work it into one of my new projects to see if I can learn it and add it to my repitoire of skills. However, I'm hitting a roadblock here.



I'm trying to see if the user's input has illegal characters in it by using the .search function as so:



if (name.search([[]?*+|{}\()@.nr]) != -1) {
...
}


However, when I try to execute the function this line is contained it, it throws the following error for that specific line:



Uncaught SyntaxError: Invalid regular expression: /[[]?*+|{}()@.

]/: Nothing to repeat


I can't for the life of me see what's wrong with my code. Can anyone point me in the right direction?


More From » regex

 Answers
14

You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:



The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:



[\[\]?*+|{}\\()@.nr]


Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.


[#91795] Tuesday, June 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;