簡體   English   中英

Java相當於JavaScript的String.match()

[英]Java equivalent of JavaScript's String.match()

JavaScript的String.match()的Java等價物是什么

我需要得到一個數組或所有匹配的列表

例:

var str = 'The quick brown fox jumps over the lazy dog';
console.log(str.match(/e/gim));

["e", "e", "e"]

http://www.w3schools.com/jsref/jsref_match.asp

檢查Regex教程

您的代碼應該與此類似:

String input = "The quick brown fox jumps over the lazy dog";
Matcher matcher = Pattern.compile("e").matcher(input);

while ( matcher.find() ) {
    // Do something with the matched text
    System.out.println(matcher.group(0));
}

看一下regex包中的PatternMatcher類。 特別是Matcher.find方法。 這不會返回數組,但您可以在循環中使用它來遍歷所有匹配項。

String.matches(String regex)是一個更直接的等價物,但只用於一次性正則表達式。 如果您將多次使用它,請按照建議堅持使用Pattern.compile

暫無
暫無

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

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