Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to capture from a character until the first period

Tags:

regex

My regex string looks something like

Your order #Q-111-111-1111. Bill amount is $100.50

How can I extract order number i.e. string between '#' and first '.'

Q-111-111-1111

I've tried:

/#(.*[^.])[.].+?/

But it's capturing upto the last dot character. I'm sure, I need to use non greedy matching but I'm unable to accomplish that.

like image 393
Priyanshu Chauhan Avatar asked Jan 18 '26 16:01

Priyanshu Chauhan


1 Answers

You can simply use the following regex:

#(.*?)\.

* is greedy - it causes the engine to repeat the preceding token as often as possible, when you append ? to .*, it'll be lazy (ungreedy), and will match until the first dot.

To demonstrate it, lets take an example:

  • #(.*)\. applied on #12-34.234-3.234. hello world

    .* will first match everything until the end of the string (d character), then it'll try to match dot, but it doesn't exist, so it'll keep backtracking untill it matches 4, then the dot is found, matched string is #1234.2343.234

  • #(.*?)\. applied on #12-34.234-3.234. hello world

    .*? will match only until 4, then the dot is found and will be matched, the laziness causes it to stop searching for more tokens to consume

like image 83
Maroun Avatar answered Jan 21 '26 09:01

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!