How to create a progressive match regular expression?

I need a regular expression that matches a string when the user enters it. This is a little hard to explain, so let me show you what I mean:

It should match this line:

"XXXX units" , where XXXX is any number.

But it should also match any substring from the beginning of this line, therefore:

 "123" "123 u" "123 uni" 

must also match.

But of course this should not match:

 "123 xx" 

It seems so simple, but I can’t understand it. This is the closest I have:

 ^\d+ ?u?n?i?t?s? 

... but this, unfortunately, also matches strings like "123us".

Can anyone help? This is javascript, so I can be limited a bit by the lack of appearance functions ...

+7
javascript regex
source share
3 answers

Just add () :

 /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/ 

Testing:

 /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/.test("123 units") -> true /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/.test("123 un") -> true /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/.test("123 ui") -> false /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/.test("12") -> true /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/.test("123 xx") -> false 
+8
source share

It doesn't look great, but it does its job ...

 ^(\d+( (u(n(i(t(s)?)?)?)?)?)?)?$ 
+1
source share

Demo here: https://regex101.com/r/uC7pX1/6

 /^\d+( (u(n(i(t(s)?)?)?)?)?)?$/ 
+1
source share

All Articles