简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM