我有一個String:
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熱心網友回復:
使用來自java.util.regex.
Pattern pattern = Pattern.compile("/.*?/");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
String match = matcher.group(0); // output
}
uj5u.com熱心網友回復:
每次,在我的情況下,對于這個 Sting,至少會出現兩個斜線
如果可以保證,則在每個/分隔符處拆分并取前三個子字串。
String str = String.format("%s%s%s",(thestra.split("((?<=\\/)|(?=\\/))")));
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 組結束.*: 任意字符任意次數
根據Holger的以下寶貴建議更新了答案:
注意,對于Java正則引擎來說,/沒有特殊意義,這里就不用轉義了。此外,由于您只期待一場比賽(.*最后確保這一點),所以replaceFirst會更慣用。并且由于沒有關于第一個/始終位于字串開頭的宣告,因此在模式前加上 ,.*?或[^/]*將是一個好主意。
uj5u.com熱心網友回復:
Pattern.compile("/.*?/")
.matcher(thestra)
.results()
.map(MatchResult::group)
.findFirst().ifPresent(System.out::println);
您可以測驗此變體:)
最好的問候, Fr0z3Nn
uj5u.com熱心網友回復:
您還可以匹配前導正斜杠,然后使用否定字符類 [^/]*來選擇匹配任何字符,除了/然后匹配尾隨正斜杠。
String thestra = "/aaa/bbb/ccc/ddd/eee";
Pattern pattern = Pattern.compile("/[^/]*/");
Matcher matcher = pattern.matcher(thestra);
if (matcher.find()) {
System.out.println(matcher.group());
}
輸出
/aaa/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321792.html
下一篇:索引除最后兩個值之外的所有值
