1

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
  • 1
    Try `^(?:(?:1[89]|[2-9]\d) ?)?m(?: ?(?:1[89]|[2-9]\d))?$`, see [demo](https://regex101.com/r/1Ho3VK/2). – Wiktor Stribiżew Jun 17 '22 at 16:44
  • @MichaelMooney Please update your question with more cases to match and don't match. We don't know how your strings can look like. So you want to validate or match e.g. `18 m testing` and how about `testing 18m` or `foo 18 m bar`... ? – bobble bubble Jun 18 '22 at 16:28
  • You can use conditionals with [PyPI regex](https://pypi.org/project/regex/#additional-features): [`\b(m ?)?(?:1[89]|[2-9]\d)(?(1)| ?m)\b`](https://regex101.com/r/85QhjX/1) – bobble bubble Sep 26 '22 at 09:46

1 Answers1

0

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563