简体   繁体   中英

Regex validate string if it does not contain more than special count of special characters

I'm developing a pattern that validates string if it does not contain more then two matches of #. here is code:

^[^\!|\@|\$|\%|\^|\&|\*|\+][\w]*([\w ]+\#[\w ]*){0,2}$

[^!|\\@|\\$|\\%|\\^|\\&|*|+]

this is group of not acceptable symbols.

additionally, the pattern should validate string in case if it contains other symbols( - _ , . / ). each symbol should have it's own counter and should not match in any position more than two times.

for example if i have s string like this:

Mcloud dr. #33/#45, some text, some text

it should be valid. but in this case should not:

Mcloud dr. ###33/$#45, ####, ----

What would you suggest ?

Given that you want to match alphanumerics characters and some special symbols ()-_,./ You have to mention them in a character class like this.

Regex: ^(?!.*([(),.#/-])\\1)([\\w (),.#/-]+)$

Explanation:

(?!.*([(),.#/-])\\1) asserts that there shouldn't be more than one character mentioned in character class. This asserts from beginning of string to end.

([\\w (),.#/-]+) matches the rest of the string for allowed characters from beginning to end.

Regex101 Demo

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