cyrus000
cyrus000

Reputation: 67

Regex to limit special character between range

I want to limit special character to maximum value. Like I want the regex to limit at most 3 special character. I am using following regex, but its not working for me. :

(^(?:[^$@!%*?&\n]*[$@!%*?&]){0-2}[^$@!%*?&\n]*$)

Upvotes: -1

Views: 484

Answers (1)

anubhava
anubhava

Reputation: 785196

You may use this regex to match max 3 special characters:

^(?:[^$@!%*?&]*[$@!%*?&]){0,3}[^$@!%*?&]*$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start non-capture group
    • [^$@!%*?&]*: Match 0 or more of any characters that are not inside [...]
    • [$@!%*?&]: Match one of these characters inside [...]
  • ){0,3}: End non-capture group. Repeat this group 0 ot 3 times
  • [^$@!%*?&]*: Match 0 or more of any characters that are not inside [...]
  • $: End

Upvotes: 1

Related Questions