简体   繁体   English

正则表达式允许使用某些特殊字符以及小节

[英]Regex to allow certain special characters along with brakets

I am working on asp.net, and having many strings for which i have to allow Alphanumeric and some special characters like -> _ - [ ] ( ) { } , . 我正在asp.net上工作,有很多字符串,我必须允许使用字母数字和一些特殊字符,例如-> _-[](){},。 I am using regex like 我正在使用正则表达式

Regex name = new Regex("(a-zA-Z0-9 _ \[ \] \) \( \{ \} \-)*");

its not working for me. 它对我不起作用。 Can any one suggest the valid regex. 任何人都可以建议有效的正则表达式。

Use a character class with anchors: 将字符类与锚点一起使用:

Regex name = new Regex(@"^[a-zA-Z0-9_[\])({}-]*$");

It will only allow string containing 0+ ASCII letters, digits or _ , [ , ] , ) , ( , { , } and - symbols. 它将只允许包含0+ ASCII字母,数字或_[])({}-符号的字符串。

Note that inside a character class the - does not have to be escaped when placed at the start/end of the character class, else you must escape it, same as the ] char is escaped in the pattern above. 请注意,在字符类内部,当放置在字符类的开始/结尾时不必-进行转义,否则,您必须对其进行转义,就像在上述模式中对] char进行转义一样。 The ] does not have to be escaped if it is at the beginning of the character class in .NET, but if you need to run the same regex on the client side, you cannot do that since JS regex requires the ] to be escaped inside a character class. 如果]不在.NET中字符类的开头,则不必转义,但是如果您需要在客户端运行相同的regex,则不能这样做,因为JS regex要求在内部转义]角色类。

If you do not want to allow empty strings, replace * with + at the end before $ . 如果不想使用空字符串,请在$之前将*替换为+

The ^ is the start of string anchor and $ is the end of string anchor. ^是字符串锚点的开始, $是字符串锚点的结束。 They make sure no chars other than those defined in the character class can be used in the string. 它们确保字符串中不能使用除字符类中定义的字符以外的其他字符。

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

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