Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to exclude first and last characters of match

I've the following string: word_word2_word3_word4

My intention is to extract only 'test2'. Using _\w*?_ as string match, I can get 'word2' as match, but I can't see a way of removing those underscores to match only 'word2'.

I can't use .split() or something like it, this value must be gathered using Regex only.

What modifications do you suggest guys?

like image 927
Sergio Figueras Avatar asked Oct 19 '25 09:10

Sergio Figueras


1 Answers

You can also use positive lookahead and lookbehind

(?<=_)\w*2(?=_)

My intention is to extract only 'test2'. Using \w*? as string match, I can get 'word2' as a match, but I can't see a way of removing those underscores to match only 'word2'.

The underscores won't be part of the matching string but will be before and after it

EDIT:

Going further, if the match string is on the beginning or end of the whole text, it won't be surrounded by underscores.

(?<=_|^)[^_]*2(?=_|$)

This one makes optional the use of underscore in this specific situation.

online test

like image 150
Caio Oliveira Avatar answered Oct 21 '25 23:10

Caio Oliveira



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!