Home > Back-end >  Regex for m18-99
Regex for m18-99

Time:06-18

I'm looking for a regex that matches the rules 18-99? m? 18-99?. Here was my attempt (1[89]|[2-9]\d) m (1[89]|[2-9]\d) but this matches anything with m.

For clarification, here are acceptable strings:

m18
18m
m 18
18 m

CodePudding user response:

You can use

^(?:(?:1[89]|[2-9]\d) ?)?m(?: ?(?:1[89]|[2-9]\d))?$

See the regex demo.

Details:

  • ^ - start of string
  • (?:(?:1[89]|[2-9]\d) ?)? - an optional sequence of 18, 19 ... 99 and an optional space
  • m - m
  • (?: ?(?:1[89]|[2-9]\d))? - an optional sequence of a space and then 18, 19 ... 99
  • ^ - end of string

If you do not want to match a string that only contains m, use

^(?!m$)(?:(?:1[89]|[2-9]\d) ?)?m(?: ?(?:1[89]|[2-9]\d))?$

where (?!m$) after ^ prevent a string like m from matching.

CodePudding user response:

This would be some nice case for conditionals, a feature that is supported by PyPI regex.

^(m ?)?(?:1[89]|[2-9]\d)(?(1)| ?m)$

See this demo at regex101 or a Python demo at tio.run

  • The first group (m ?)? is matched optionally
  • (?(1)| ?m) if group one did not succeed |match that

(assuming you don't want to allow m alone without number)

  • Related