I need a regex that does the following:
- Repeat any number x amount of times
- Ignore characters and do not count them (example: whitespace and '/')
This is the regex I have right now: [0-9]{0,5}
However, it does not cover the following legit strings:
1 2 3 4 5
123/45
1234 5
1 234 4
1/234/5
1/234 5
1 2/3 4/5
1 2345
1 ////23/////45
I tried:
[\s*\/*0-9]{0,5} //counts unwanted characters
[0-9\s\/]{0,5} //counts unwanted characters
[0-9-\s \/]{0,5} //counts unwanted characters
[\s \/-]{0,}[0-9]{0,5} // does not mix
Is this even possible in regex?
The other solution, I can do is to remove these characters and then comparing to the pattern.
CodePudding user response:
The regex you can use is
(?:[ \/]*\d){0,5}
See the regex demo. Details:
(?:
- start of a non-capturing group:[ \/]*
- zero or more spaces or slashes\d
- a digit
){0,5}
- end of the group, match zero to five times.
If you need to match any spaces or slashes after the last digit, add [ \/]*
at the end:
(?:[ \/]*\d){0,5}[ \/]*