2015-11-17 55 views
0

我有一個這樣的字符串:如何在不刪除Java中字符串的任何字符的情況下分割字符串?

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

我必須把它分成幾個大塊:

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

用含有lookarounds一個正則表達式。 –

+0

你可以使用一個模式和匹配器,但它會增加複雜性 – MadProgrammer

+0

或任何「零寬度」斷言,如'\ b'(和是週轉)。 –

回答

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

相關問題