![](/img/trans.png)
[英]How to get the next n fridays which are the first, second or third friday in a month?
[英]Substring first, second, third, ... , n match
鑒於: String s = "{aaa}{bbb}ccc
。
如何獲取一個數組(或列表)哪些元素將是:
第 0 個元素: aaa
第一個元素: bbb
第二個要素: ccc
這是我的嘗試:
String x = "{aaa}{b}c";
return Arrays.stream(x.split("\\}"))
.map(ss -> {
Pattern pattern = Pattern.compile("\\w*");
Matcher matcher = pattern.matcher(ss);
matcher.find();
return matcher.group();
})
.toArray(String[]::new);
(假設只允許 Java <= 8)
這種方式比使用正則表達式要簡單一些(也可能快一點):
String[] strings = new String[100];
int index = 0;
int last = 0;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == "}"){
strings[index++] = s.substring(last + 1, i - 1);
last = i + 1;
}
}
strings[index++] = s.substring(last, s.length());
如果你想使用正則表達式,模式需要識別一個或多個字母的序列,你可以嘗試模式(?:{([az]+)})*([az]+)
。
private static List<String> parse ()
{
String x = "{aaa}{b}c";
Pattern pattern = Pattern.compile ("[^{\\}]+(?=})");
List < String > allMatches = new ArrayList < String > ();
Matcher m = pattern.matcher (x);
while (m.find ())
{
allMatches.add (m.group ());
}
String lastPart = x.substring(x.lastIndexOf("}")+1);
allMatches.add(lastPart);
System.out.println (allMatches);
return allMatches
}
確保檢查 lastIndexOf >-1,如果您的字符串可能包含也可能不包含沒有大括號的最后一部分。
如果您的字符串像您的示例一樣格式良好,那么簡單的替換就足夠了:
String[] myStrings = {"{aaa}bbb", "{aaa}{bbb}{ccc}ddd", "{aaa}{bbb}{ccc}{ddd}eee"};
for(String str : myStrings){
String[] splited = str.replace("}{", "}").replace("{", "").split("}");
System.out.println(Arrays.toString(splited));
}
印刷:
[aaa, bbb]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.