我有一個字串:
String thestra = "/aaa/bbb/ccc/ddd/eee";
每次,在我的情況下,對于這個 Sting,至少會出現兩個斜線。
我得到了/aaa/下面的結果,它是/字串中字符的“前兩次出現”之間的子字串。
System.out.println("/" thestra.split("\\/")[1] "/");
它解決了我的目的,但我想知道是否還有其他優雅和清潔的替代方法?
請注意,我需要在aaa. IE/aaa/
uj5u.com熱心網友回復:
您可以使用indexOf,它接受索引的第二個引數以從以下位置開始搜索:
int start = thestra.indexOf("/");
int end = thestra.indexOf("/", start 1) 1;
System.out.println(thestra.substring(start, end));
它是否更優雅是一個見仁見智的問題,但至少它不會/在字串中找到每個或創建一個不必要的陣列。
uj5u.com熱心網友回復:
Scanner::findInLine 可以使用回傳模式的第一個匹配項:
String thestra = "/aaa/bbb/ccc/ddd/eee";
System.out.println(new Scanner(thestra).findInLine("/[^/]*/"));
輸出:
/aaa/
uj5u.com熱心網友回復:
每次,在我的情況下,對于這個 Sting,至少會出現兩個斜線
如果可以保證,則在每個/分隔符處拆分并取前三個子字串。
String str = String.format("%s%s%s",(thestra.split("((?<=\\/)|(?=\\/))")));
uj5u.com熱心網友回復:
Pattern.compile("/.*?/")
.matcher(thestra)
.results()
.map(MatchResult::group)
.findFirst().ifPresent(System.out::println);
您可以測驗此變體:)
最好的問候, Fr0z3Nn
uj5u.com熱心網友回復:
使用來自java.util.regex.
Pattern pattern = Pattern.compile("/.*?/");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String match = matcher.group(0); // output
}
uj5u.com熱心網友回復:
可以有很多方法,例如用正則運算式的group#1 替換字串,(\/[^\/].*?\/).*如下所示:
public class Main {
public static void main(String[] args) {
String thestra = "/aaa/bbb/ccc/ddd/eee";
String result = thestra.replaceAll("(\\/[^\\/].*?\\/).*", "$1");
System.out.println(result);
}
}
輸出:
/aaa/
正則運算式的解釋:
(: 第 1 組開始\/: 人物,/[^\/]: 不是性格,/.*?: 任意次數的任意字符(惰性匹配)\/: 人物,/
): 第 1 組結束.*: 任意字符任意次數
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318343.html
