[英]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}
可能看起來像\\\\{[^}]*\\\\}
。 Pattern
和Matcher
類,您可以找到與此正則表達式匹配的每個子字符串。 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.