2014-02-18 16 views
3

源字符串中花括號內有一個字符串對象在Java中,其內容爲字符串數組:如何獲取在Java

String sourceString="This {is} a sample {string} that {contains} {substrings} inside curly {braces}"; 

我想字符串,其內容爲數組:{is},{string},{contains},{substrings}{braces}

下面是我寫的,以獲得結果的代碼,但我得到的輸出是:

"{is} a sample {string} that {contains} {substrings} inside curly {braces}" 

所以,基本上是採取一切都在betw人物首先打開大括號,最後關閉大括號。

// Source string 
String sourceString="This {is} a samle {string} that {contains} {substrings} inside curly {braces}"; 

// Regular expression to get the values between curly braces (there is a mistake, I guess) 
String regex="\\{(.*)\\}"; 
Matcher matcher = Pattern.compile(regex).matcher(sourceString); 

while (matcher.find()) { 
    System.out.println(matcher.group(0)); 
} 
+4

歡迎StackOverflow上。你有沒有嘗試過這個問題呢?如果是,請向我們展示您的代碼。如果沒有,那麼我們建議你先自己嘗試一下,然後無論你卡在哪裏,我們都樂意提供幫助。 –

+0

你想保留大括號嗎? – Bohemian

+0

@Bohemian:OP說:*我想要的字符串數組的內容爲:{是},{字符串},{包含},{子字符串} {大括號} *。 –

回答

5

谷歌搜索一點點發現this的解決方案,這給了我的想法,圖案

Lesson: Regular Expressions花了一些時間把我需要提供這個例子中,庫和功能...

String exp = "\\{(.*?)\\}"; 

String value = "This {is} a samle {string} that {contains} {substrings} inside curly {braces}"; 

Pattern pattern = Pattern.compile(exp); 
Matcher matcher = pattern.matcher(value); 

List<String> matches = new ArrayList<String>(5); 
while (matcher.find()) { 
    String group = matcher.group(); 
    matches.add(group); 
} 

String[] groups = matches.toArray(new String[matches.size()]); 
System.out.println(Arrays.toString(groups)); 

,輸出

[{is}, {string}, {contains}, {substrings}, {braces}] 
0
  • 匹配{characters}的模式可能看起來像\\{[^}]*\\}
  • 現在使用PatternMatcher類可以找到與此正則表達式匹配的每個子字符串。每個子創辦的
  • 將在List<String>
  • 列表後充滿你可以將其轉換爲使用yourList.toArray(newStringArray)法陣所有子。

編輯您更新後

問題與您正則表達式是*量詞是貪婪的,這意味着它會試圖找到最大可能的解決方案。所以在\\{(.*)\\}情況下,它會匹配

  • 第一可能{
  • 零個或多個字符
  • 最後可能}這在

    This {is} a samle {string} that {contains} {substrings} inside curly {braces} 
    
    情況下

意味着它將開始的{}的finis自{braces}

爲了*找到最小的字符集,可用於創建匹配的子你需要它做*?量詞不願意,

  • 描述你的正則表達式,像我一樣原本後要麼

    • 添加?和從可能的匹配排除}{}之間,所以不是匹配表示.使用[^}]其表示除了任何字符的任何字符。
  • +0

    如果你對這個解決方案的某些部分有麻煩,請隨時提出更具體的問題。 – Pshemo

    1

    這裏是一個在線解決方案:

    String[] resultArray = str.replaceAll("^[^{]*|[^}]*$", "").split("(?<=\\})[^{]*"); 
    

    該作品以第一剝離的開頭和結尾的垃圾,然後一切分裂}{之間。


    下面是一些測試代碼:

    String str = "This {is} a samle {string} that {contains} {substrings} inside curly"; 
    String[] resultArray = str.replaceAll("^[^{]*|[^}]*$", "").split("(?<=\\})[^{]*"); 
    System.out.println(Arrays.toString(resultArray)); 
    

    輸出:

    [{is}, {string}, {contains}, {substrings}] 
    
    +0

    咦? Downvoted?爲什麼?這是一個很好的答案恕我直言。 – Bohemian