Home > Back-end >  Using Regex to only accept x amount of a certain character
Using Regex to only accept x amount of a certain character

Time:10-29

I have this Regex pattern:

\b(?:[A-Z\d] [\/\-]) [A-Z\d] \b

And it collects everything I need perfectly, but then also grabs some things I don't want. I'm wondering how to write in there something like I do want to accept "-", but no more than 5 at a time. Same with "/" but maybe no more than 1 for those. Here's an example of what it's grabbing that I do want vs what it's grabbing that I don't want:

Yes:

AIR-CT2504-50-K9
1000BASE-T
ISR4451-X-SEC/K9

No:

0/1/10/5/50
2B108-250A-2B-2B-2B-250A-2B-2B-2B-250A-2B-2B
2022/10/28

CodePudding user response:

If you don't want partial matches, you might use anchors and exclude a certain number of hyphens or forward slashes.

As the strings do not seems to contain spaces, and you can mix - and /:

^(?!(?:[^\s-]*-){5})(?!(?:[^\s\/]*\/){2})(?:[A-Z\d] [\/-]) [A-Z\d] $

The pattern matches:

  • ^ Start of string
  • (?!(?:[^\s-]*-){5}) Assert not 5 hyphens where [^\s-] matches a non whitespace char except for -
  • (?!(?:[^\s\/]*\/){2}) Assert not 2 forward slashes
  • (?:[A-Z\d] [\/-]) Repeat 1 times matching 1 chars A-Z or digits followed by either / or -
  • [A-Z\d] match 1 chars A-Z or a digit
  • $ End of string

Regex demo

  • Related