ForJ9
ForJ9

Reputation: 745

Split regex; keep delimiter

I have a text looks like that:

This is [!img|http://imageURL] text containing [!img|http://imageURL2] some images in it

So now I want to split this string in parts and keep the delimiters. I already figured out, that this works, to split the string, but it don't keep the delimiters:

\[!img\|.*\]

And in some other posts I see that I need to add ?<= to keep the delimiter. So I connected both, but I get the error message: Lookbehinds need to be zero-width, thus quantifiers are not allowed Here's the full regex throwing this error:

(?<=\[!img\|.*\])

I expect as result:

[This is; [!img|http://imageURL]; text containing; [!img|http://imageURL2]; some images in it]

So whats the best way to fix it?

Upvotes: 1

Views: 150

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

You can use a combination of lookaround assertions:

String[] splitArray = subject.split("(?<=\\])|(?=\\[!img)");

This splits a string if the preceding character is a ] or if the following characters are [!img.

Upvotes: 2

Related Questions