In regex, I can match zero or more occurrences with *
, and between 7 and 50 occurrences with {7,50}
. How can I match either zero or between 7 and 50 occurrences?
Asked
Active
Viewed 417 times
-2

gkeenley
- 6,088
- 8
- 54
- 129
2 Answers
1
Group the range match and make it optional with ?
(match 0 or 1 instance).
Python, since a language wasn't specified:
>>> import re
>>> test = 'abaxbaxxxxxxbaxxxxxxxbaxxxxxxxxb'
>>> re.findall('a(?:x{7,50})?b',test)
['ab', 'axxxxxxxb', 'axxxxxxxxb']
- Match
a
. (?:n)
matchn
but don't make a capture group.grouping.(?:x{7,50})
groups match 7-50 occurrences ofx
.(?:x{7,50})?
makes it optional (0 or 1 occurrence)- Match
b
Without the non-capturing group you'd get:
>>> re.findall('a(x{7,50})?b',test)
['', 'xxxxxxx', 'xxxxxxxx']
See a working example @ https://regex101.com/r/qkziuu/1

Mark Tolonen
- 166,664
- 26
- 169
- 251