[英]Java equivalent of JavaScript's String.match()
What is the Java equivalent of JavaScript's String.match()
JavaScript的
String.match()
的Java等价物是什么
I need to get an array or a list of all matches 我需要得到一个数组或所有匹配的列表
Example: 例:
var str = 'The quick brown fox jumps over the lazy dog';
console.log(str.match(/e/gim));
gives 给
["e", "e", "e"]
http://www.w3schools.com/jsref/jsref_match.asp http://www.w3schools.com/jsref/jsref_match.asp
Check Regex tutorial 检查Regex教程
Your code should look something similar to this: 您的代码应该与此类似:
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));
}
Take a look at the Pattern
and Matcher
classes in the regex
package. 看一下
regex
包中的Pattern
和Matcher
类。 Specifically the Matcher.find
method. 特别是
Matcher.find
方法。 That does not return an array, but you can use it in a loop to iterate through all matches. 这不会返回数组,但您可以在循环中使用它来遍历所有匹配项。
String.matches(String regex)
is a more direct equivalent, but only use it for one-off regexes. String.matches(String regex)
是一个更直接的等价物,但只用于一次性正则表达式。 If you'll be using it multiple times, stick with Pattern.compile
as suggested. 如果您将多次使用它,请按照建议坚持使用
Pattern.compile
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.