简体   繁体   English

在 RegEx 中检测角括号和大括号

[英]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 method always returns false if I include them in the pattern I have.我尝试包含这些,但如果我将它们包含在我拥有的模式中, IsMatch方法总是返回 false。 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. IsMatch返回 false 。 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如果您希望您的正则表达式可移植,请将右方括号放在首位,连字符放在最后,如下所述: http://www.regular-expressions.info/posixbrackets.html

pattern = "^([][_,A-Za-z0-9 !@#$%^&(){}=+;'.~`-]{1,60})$";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM