简体   繁体   中英

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 -> _ - [ ] ( ) { } , . 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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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