简体   繁体   English

如何在Java中保留分隔符的同时在不同的分隔符之间拆分文本?

[英]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 例如,如果我的文本包含: 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'] 我设法实现的是一个看起来像这样的数组: ['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. 但说实话split ,甚至regex可能不是你要找的工具。 Try to think of building your own parser/state machine instead. 尝试考虑构建自己的解析器/状态机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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