Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching between last occurence of character and another character

Tags:

regex

Hello I'm trying to get the following results from my regex. I need the characters between the last occurrence of "_" and a period. I've got this regex [^_]+$ but its not getting rid of the ".pdf" at the end.

Desired output

Original string: SalesOrder_359959_929058.pdf After regex: 929058

like image 222
mgmedick Avatar asked Nov 23 '25 23:11

mgmedick


1 Answers

Try this:

([^_.]+)\.

This will match one or more of any character other than _ or . in group 1, followed by a .. You then just have to extract group 1 to get the substring you want.

If your regex engine supports lookaheads, you could also use this:

[^_.]+(?=\.)

This will match one or more of any character other than _ or . so long as it is immediately followed by a ., but the . itself is not captured.

Of course, both methods could fail if you have multiple . in your string. In that case you might use something like this:

([^_.]+)\.[^_.]*$

Or this:

[^_.]+(?=\.[^_.]*$)
like image 175
p.s.w.g Avatar answered Nov 27 '25 13:11

p.s.w.g



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!