Gops AB Gops AB - 4 months ago 13
Java Question

Java - Pattern matching between the same pattern

My sample string:

a ghgduysgd a fdferfdf a bvfxbgdf a gdfgdfg


I need to find all the contents between a's.

I have
(?<=a).*
But it matches all the contents after a. But I want to find between a.

First iteration:
ghgduysgd


Second iteration:
fdferfdf


I want to get data like the above for the manipulation. can you help with regex?

Answer

You alrady use a lookbehind in your regex, change it to also use a lookahead:

(?<=a).*(?=a|$)

Then make the .* non-greedy to stop at the first available "ending" a:

(?<=a).*?(?=a|$)

EDIT: the a|$ is from tobias_k's comment below, originally it was just a