Make mandatory group in JavaScript regex

My string requirement is m+/-n.n. it will accept string m plus(+) or minus(-) any integer or decimal number. i.e, m+1, m+.1, n+0.1, m+1.1, similar with minus(-) sign.

I tried with regex pattern '^(?:m|M)[+-](\d{1,})?(\.\d{1,0})?$'

Here the problem is it is also accepting ‘m+’ or ‘m-‘, which should not be. Here, after [+-] there are two groups, both are individually optional, which is required to support .1, 0.1, 1, 1.1. Want to convert those two groups into one group and make it mandatory.


One way could be to add a lookahead before the two groups:


Here I added (?=[d.]), which asserts that there must be either a . or a d after the [+-], but does not consume it, as it should be consumed by the optional groups after the lookahead.

Regex Demo