-2

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?

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

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) match n but don't make a capture group.grouping.
  • (?:x{7,50}) groups match 7-50 occurrences of x.
  • (?: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
0

you can use this regex

(\S{7,50})?

\S{7,50} means 7 to 50 occurrence of non-whitespace character

(\S{7,50})? means 0 or 1 occurrence of \S{7,50}

Nameless
  • 503
  • 3
  • 21