繁体   English   中英

java split regex:在大括号之间使用任何文本分割字符串并保留定界符

[英]java split regex: split string using any text between curly brackets and keep the delimiter

由于这里有另一个问题,我几乎满足了我的需要,但不是很清楚。

我正在尝试使用Java的String.split()分解字符串并保留正则表达式定界符。 我的定界符不是一个字符。 例:

hello {world} this is {stack overflow} and this is my string

需要分为以下数组:

hello

{world}

this is

{stack overflow}

and this is my string

我可以使用{[^}]+}匹配{和}之间的所有文本,并使用它拆分字符串。 但是我确实也需要将文本保持在{和}之间。

尝试以这种方式拆分

yourString.split("\\s(?=\\{)|(?<=\\})\\s")

它将在每个后面有{或之前}空间上分割。


演示版

for (String s : "hello {world} this is {stack overflow} and this is my string"
        .split("\\s(?=\\{)|(?<=\\})\\s")) 
    System.out.println(s);

输出

hello
{world}
this is
{stack overflow}
and this is my string

暂无
暂无

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

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