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...
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 /.
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...
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.
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!
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
Demo here: https://regex101.com/r/uC7pX1/6
/^\d+( (u(n(i(t(s)?)?)?)?)?)?$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With