簡體   English   中英

如何獲取java中源字符串中大括號內的字符串數組

[英]how to get the array of strings that are inside curly braces in the source string in 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}"

所以,基本上它是在第一個打開的花括號和最后一個花括號之間的所有字符。

// 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));
}

一點點谷歌搜索找到了這個解決方案,它給了我關於模式的想法

有一些時間用於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}]

這是一線解決方案:

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}]
  • 匹配{characters}可能看起來像\\\\{[^}]*\\\\}
  • 現在使用PatternMatcher類,您可以找到與此正則表達式匹配的每個子字符串。
  • 將每個已創建的子字符串放在List<String>
  • 在列表填充了所有子字符串后,您可以使用yourList.toArray(newStringArray)方法將其轉換為數組。

更新后編輯

你的正則表達式的問題是*量詞是貪婪的,這意味着它會試圖找到最大可能的解決方案。 因此,在\\\\{(.*)\\\\} ,它將匹配

  • 第一個可能{
  • 零個或多個字符
  • 最后可能}以防萬一

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

意味着它將從{braces} { in {is}和finis in }開始

要使*找到可用於創建匹配子字符串的最小字符集,您需要

  • ? 制作完成后*? 量詞不情願,
  • 描述你的正則表達式,像我一樣原本並排除}從可能的匹配之間{}所以,與其匹配其代表任意字符. 使用[^}]表示除}之外的任何字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM