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

How can we split a string without removing any characters from the string in Java?

我有这样的字符串:

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

我必须把它分成几块:

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

您可以使用此拆分:

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

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

RegEx Demo

正则表达式分解:

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

Read about look arounds in regex