如何在不从Java中的字符串中删除任何字符的情况下拆分字符串?

时间:2015-11-17 21:11:31

标签: java regex split string-split

我有一个这样的字符串:

String str = "How {$can} {$we} split this {$string}?";

我必须把它分成几个块:

["How ","{$can}"," ","{$we}"," split this ","{$string}","?"]

1 个答案:

答案 0 :(得分:4)

您可以使用此拆分:

String str = "How {$can} {$we} split this {$string}?";

String[] arr = str.split("(?=\\{)|(?<=\\})");

RegEx Demo

RegEx分手:

(?=\\{)   # if next char is {
|         # regex alternation
(?<=\\})  # if previous char is }

Read about look arounds in regex