Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX: Select all text between last underscore and dot

I'm having trouble retrieving specific information of a string.

The string is as follows:

20190502_PO_TEST.pdf

This includes the .pdf part. I need to retrieve the part between the last underscore (_) and the dot (.) leaving me with TEST

I've tried this:

[^_]+$

This however, returns: TEST.PDF

I've also tried this:

_(.+)\.

This returns: PO_TEST

like image 544
Bram Terlouw Avatar asked Nov 24 '25 21:11

Bram Terlouw


1 Answers

This pattern [^_]+$ will match not an underscore until the end of the string and will also match the .

In this pattern _(.+). you have to escape the dot to match it literally like _(.+)\. see demo and then your match will be in the first capturing group.

What you also might use:

^.*_\K[^.]+
  • ^.*_ Match the last underscore
  • \K Forget what was matched
  • [^.]+ Match 0+ times not a dot

Regex demo

like image 174
The fourth bird Avatar answered Nov 27 '25 15:11

The fourth bird



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!