Search code examples
regexclish

right square bracket in regex, can't be escaped?


I am using clish and regular expressions for parameter entry. http://clish.sourceforge.net/clish-0.7.3/group__clish__ptype.html

I am whitelisting characters like so:

 pattern="[a-zA-Z0-9\!\[\£\$\%\/\^\_\+\=\#\@\;\,\|\*\{\}\(\)\~\.\>\<\&\-]+"

This works fine, I can enter any of the specified characters. However if I add \] or \\] to escape a right square bracket this is not working. It is matching the [ and therefore can not be entered, not anything after the ]. Any ideas how to escape it so as to enter ] as a valid character? [ works fine.


Solution

  • Try this pattern

    pattern="[][a-zA-Z0-9!£$%/^_+=#@;,|*{}()~.&-]+"
    

    The literal closing square bracket must be at the first position in the character class to avoid ambiguity with the closing square bracket that closes the character class (since an empty character class is not allowed). You can put the opening square bracket anywhere you want (obviously not at the first position, or after the -)