-1

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.

md123
  • 295
  • 3
  • 8
  • If the string were `Y|ZXIET` would you want `ZXIET` returned or a conclusion that there is no match? – Cary Swoveland Apr 11 '20 at 04:44
  • None of the answers in the answer marked as duplicate matches the accepted answer here, why closing as duplicate? – Andronicus Apr 11 '20 at 09:35
  • @Andronicus, I agree, so am voting to reopen. The cited earlier question suggests the answer is merely to change a match from greedy to non-greedy. That was my initial impression, but as I explained in my answer, that is not sufficient. – Cary Swoveland Apr 11 '20 at 10:10
  • md123, kindly answer my question. – Cary Swoveland Apr 11 '20 at 10:13

2 Answers2

3

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.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
1

It's perhaps easiest to just match the regular expression

(?<=Y\|)[^|]*

Demo

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\|).*?(?=\|)

Demo

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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • After posting I noticed that the regex I suggested is very similar to the one @Andronicus gave earlier. I will leave my answer for the discussion about modifying the OP's regex. – Cary Swoveland Apr 11 '20 at 04:48