Sergio Figueras Sergio Figueras - 24 days ago 14
Java Question

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?

Answer

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 match, but I can't see a way of removing those underscores to match only 'word2'.

The underscores wont be part of the maching 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 wont be surrounded by underscores.

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

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

online test