Detecting angle and curly brackets in RegEx
I have a regular expression to validate a text box to only allow particular characters. The expression currently I have is
pattern = "^([-_,A-Za-z0-9 !@#$%^&()=+;'.~`]{1,60})$";
to report an error if a character other than is input. This works perfectly. Now I want to allow [
, ]
, {
and }
(the square and curly brackets) as valid characters. I tried including these but the IsMatch
metho开发者_运维问答d always returns false if I include them in the pattern I have. I added them as follows,
pattern = "^([-_,A-Za-z0-9 !@#$%^&()[]{}=+;'.~`]{1,60})$";
I tested this for only alpha numeric string value. IsMatch
returns false on that too. I pretty sure I am doing something wrong with the new thing included.
Can any one let me know what's wrong in the modified pattern?
You need to escape the square brackets inside the square brackets.
pattern = "^([-_,A-Za-z0-9 !@#$%^&()\[\]{}=+;'.~`]{1,60})$";
BTW: {} are braces, or curly braces, not angle brackets.
If you want your regex to be portable, put the closing square bracket first and hyphen last, as discussed here: http://www.regular-expressions.info/posixbrackets.html
pattern = "^([][_,A-Za-z0-9 !@#$%^&(){}=+;'.~`-]{1,60})$";
精彩评论