1

I'm new to regex, so I've done a bit research. My filter should only allow:

  • a-Z
  • 0-9 (meaning 0 to 9)
  • ()
  • []

I've found this regex:

"/^[a-zA-Z0-9]+$/"

I edited it to allow ()

"/^[a-zA-Z0-9()]+$/"

But how to make the regex allowing [] too? Seems like [] need to be escaped somehow.

seikzer
  • 111
  • 1
  • 1
  • 8

2 Answers2

1

The character \ is the escape character in regex. Try this:

"/^[a-zA-Z0-9()\[\]]+$/"
e_i_pi
  • 4,590
  • 4
  • 27
  • 45
1

You do not need to escape the square brackets if you put them first, like so:

^[][a-zA-Z0-9()]+$

See a demo on regex101.com.
Please also note that a-Z is not the same as a-zA-Z, see the famous answer from @Wiktor here for more details.

Jan
  • 42,290
  • 8
  • 54
  • 79