0

I am trying to match the list of symbols in regex but somehow the result is always returning with errors

symbol list = !@#$+*{}?<>&’”[]=%^

    if (text.match('^[\[\]\!\"\#\$\%\&\'\(\)\*\+\,\/\<\>\=\?\@\[\]\{\}\\\\\^\_\`\~]+$')) { 
      this.specialChar = true;
    } else {
      this.specialChar = false;
    }

I am getting the following error:

Invalid regular expression: /^[[]!"#$%&'()*+,/<>=?@[]{}\\^_`~]+$/: Nothing to repeat

How do I correctly match the symbols in regex? basically I want to check if text contain any of those symbols.

logger
  • 1,983
  • 5
  • 31
  • 57
  • You want to match the whole chars or at least one of them? – Ele Oct 22 '18 at 17:04
  • I see a string, not a regular expression. I would expect to see `...match(/^...../)` – epascarello Oct 22 '18 at 17:05
  • least one of them so if text = 'some text + sometext' the expression should return true since '+' was in the text – logger Oct 22 '18 at 17:07
  • In your string literal, all backlashes that do not form a valid escape sequence with the subsequent char get removed. You need to double escape them, or better use a *regex literal*. – Wiktor Stribiżew Oct 22 '18 at 17:10

1 Answers1

0

You should use this regex constructor instead:

   if (text.match(/^[\[\]\!\"\#\$\%\&\'\(\)\*\+\,\/\<\>\=\?\@\[\]\{\}\\\\\^\_\`\~]+$/)) { 
      this.specialChar = true;
    } else {
      this.specialChar = false;
    }

The reason it fails is that you use a regex string constructor. If you still want to do that, you need to DOUBLE escape the characters, like this:

if (text.match('^[\\[\\]\\!\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\/\\<\\>\\=\\?\\@\\[\\]\\{\\}\\\\\\^\\_\\`\\~]+$')) { 

Now you will create a valid regex.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57