Ross Drew Ross Drew -4 years ago 42
Java Question

Can regex extract a substring, specifically after another without including the first?

(Edit, I said 'digit', I should have said 'alphanumeric char')

How do I extract a postfix from a string from a list of possibles (

,X
,
,Y
,
,X)
,
),Y
). All need to be preceded by a alphanumeric character to be valid but the character is not to be extracted:-

What I am using is
\w(,X|,Y|,X\)|\),Y){1}$
but this includes the preceding character (
\w
) in the extracted value.

(Unit tests pass but it's not sophisticated enough to test the returned match)
https://regex101.com/r/4Ggu7z/5/tests

Answer Source

Converting my comment to an answer.

You can use a negative lookahead instead of matching digit in your regex. Here is working regex:

(?<=\w)(,[XY]|,X\)|\),Y)$

RegEx Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download