Java regex question: How to match a sting from N-th field in a line using regex?

Viewed 37

I am trying to match string "RAV" on every line on 15th word. Each word is delimited by "|" (pipe). I need to compare if line has this string or not. If yes, I will proceed with my next step.

I was trying this

((((?:[^|]*\|){17}(.*?)\|)+\|[^|]*$)|[^|]+(?=(\,\H\,))|(^([0-9]){4})|(([RAV]){3}))

But this one matches even if I have "RAV" first, second or any other fields.

I need to match exactly on 15th field.

1 Answers

You could match the first 14 words, and then capture the 15th word after the pipe.

If you want to prevent a partial word, you can always append a word boundary (RAV)\b

^(?:\w+\|){14}(RAV)

Regex demo

Or using a negated character class, but that can match more that 1 word between the pipes:

^(?:[^|]+\|){14}(RAV)

Regex demo

Related