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 ?

Upvotes: 2

Views: 1540

Answers (1)

Rahul
Rahul

Reputation: 2748

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

Upvotes: 3

Related Questions