String: Y|ZXIET|V| |N|100|Y||ZXIET|ZXIET|Nl
Need to get first ZXIET
.
I've tried this (?<=Y\|)(.*)(?=\|)
. It gets it right for the first Y\|
, but it takes the last |
character, instead of the first one.
String: Y|ZXIET|V| |N|100|Y||ZXIET|ZXIET|Nl
Need to get first ZXIET
.
I've tried this (?<=Y\|)(.*)(?=\|)
. It gets it right for the first Y\|
, but it takes the last |
character, instead of the first one.
For the example you provided even simple ([A-Z])\w+
does the job.
What you're looking for is (?<=Y\|)([^|]*)
. It matches every character but |
in the second group.
It's perhaps easiest to just match the regular expression
(?<=Y\|)[^|]*
and take the first match. This matches ZXIET
after "Y|"
and an empty string after the second "Y|"
.
Alternatively, suppose you simply added a question mark to (.*)
in the regex your tried, to make it non-greedy, causing it to stop immediately before the first, rather than last, "|"
:
(?<=Y\|)(.*?)(?=\|)
Moreover, there really is no point in having a capture group, as it will simply return the match, which you get anyway:
(?<=Y\|).*?(?=\|)
With the example that matches ZXIETV
and |ZXIET
. However, if the example string were
Y||ZXIETV| |N|100|Y||ZXIET|ZXIET|Nl
the first match would be |ZXIETV
which is probably not what you want. I therefore suggest you use the first regex I suggested.