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
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
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 spacem
- m
(?: ?(?:1[89]|[2-9]\d))?
- an optional sequence of a space and then 18
, 19
... 99
^
- end of stringIf 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.