简体   繁体   中英

How to split text between different delimiters while keeping delimiters in Java?

Is it possible to split text with different delimiters while keeping delimiters in place in returned array.

In example if I have a text that consist of : sin({$=i$}^2

and I want to split it in an array that looks like this :

['sin(' , '{$=i$}', '^2']

while my delimiters are { and } . What I managed to achieve is an array that looks like this : ['sin(' , '{$=i$', '}^2']

but I can't make that last one delimiter } in right place with this piece of code :

String text = "sin({$=i$}^2";
String[] splitted = text.split("(?=[{}])");

Based on your example it looks like you may be looking for

split("(?<=\\})|(?=\\{)")

We are using look-around mechanisms to

  • (?<=\\\\}) split at place which has } before it (which means split after } )
  • (?=\\\\{) split at place which has { after it (which means split before { )

But to be honest split or even regex may not be tool you are looking for. Try to think of building your own parser/state machine instead.

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