Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a "progressively matching" regex?

I need a regex that matches a string as the user types it. It's a bit hard to explain, so let me show what I mean:

It should match this string:

"XXXX units", where XXXX is any number.

But it should also match any substring from the beginning of that string, so:

"123"
"123 u"
"123 uni"

should also match.

But of course, this should not match:

"123 xx"

It seems so simple, but I can't quite figure it out. This is the closest I've got:

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

...but that unfortunately also matches strings like "123us".

Can anyone help? It's javascript, so I may be a bit limited by missing look behind/ahead features...

like image 274
Zissou Avatar asked Dec 07 '15 17:12

Zissou


People also ask

Can you match non-printable characters in regex?

Notice that you can match also non-printable characters like tabs , new-lines , carriage returns . We are learning how to construct a regex but forgetting a fundamental concept: flags. A regex usually comes within this form / abc /, where the search pattern is delimited by two slash characters /.

How to use regex generator?

Regex Generator 1 Paste a text sample. Give us an example of the text you want to match using your regex. ... 2 Which parts of the text are interesting for you? Character (.) Character (.) Character (.) Character (.) 3 Hover the generated regular expression to see more information. ... More items...

How do I make regex match in case-insensitive mode?

By default, all major regex engines match in case-sensitive mode. If you want patterns such as Name: [a-z]+ to match in case-insensitive fashion, we need to turn that feature on. * By default, the dot . doesn't match line break characters such as line feeds and carriage returns.

What is [regex]::matches()?

Using $matches like we did in the previous posts means we have to write a lot of looping and if statements. With [regex]::matches() we can condense all that and it could work on a big blob of text instead of just a list of individual lines. This means that if there is more than 1 match per line we can still get it!


2 Answers

Just add some ():

/^\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
like image 75
Kenney Avatar answered Sep 19 '22 21:09

Kenney


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

/^\d+( (u(n(i(t(s)?)?)?)?)?)?$/
like image 20
CoderPi Avatar answered Sep 20 '22 21:09

CoderPi