Answers:
(如果您可以假设Java> = 9,那么4castle的答案比下面的要好)
您需要创建一个匹配器,并使用它来迭代查找匹配项。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("your regular expression here")
.matcher(yourStringHere);
while (m.find()) {
allMatches.add(m.group());
}
之后,allMatches
包含匹配项,allMatches.toArray(new String[0])
如果您确实需要一个数组,则可以使用它来获取一个数组。
MatchResult
由于Matcher.toMatchResult()
返回了当前组状态的快照,因此您还可以编写辅助函数来循环匹配。
例如,您可以编写一个惰性迭代器来完成
for (MatchResult match : allMatches(pattern, input)) {
// Use match, and maybe break without doing the work to find all possible matches.
}
通过做这样的事情:
public static Iterable<MatchResult> allMatches(
final Pattern p, final CharSequence input) {
return new Iterable<MatchResult>() {
public Iterator<MatchResult> iterator() {
return new Iterator<MatchResult>() {
// Use a matcher internally.
final Matcher matcher = p.matcher(input);
// Keep a match around that supports any interleaving of hasNext/next calls.
MatchResult pending;
public boolean hasNext() {
// Lazily fill pending, and avoid calling find() multiple times if the
// clients call hasNext() repeatedly before sampling via next().
if (pending == null && matcher.find()) {
pending = matcher.toMatchResult();
}
return pending != null;
}
public MatchResult next() {
// Fill pending if necessary (as when clients call next() without
// checking hasNext()), throw if not possible.
if (!hasNext()) { throw new NoSuchElementException(); }
// Consume pending so next call to hasNext() does a find().
MatchResult next = pending;
pending = null;
return next;
}
/** Required to satisfy the interface, but unsupported. */
public void remove() { throw new UnsupportedOperationException(); }
};
}
};
}
有了这个,
for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
System.out.println(match.group() + " at " + match.start());
}
产量
a at 0 b at 1 a at 3 c at 4 a at 5 a at 7 b at 8 a at 10
ArrayList
和进行基准测试LinkedList
,结果可能令人惊讶。
allMatches
vs 长度的总和yourStringHere.length()
),则可以为计算一个合适的大小allMatches
。根据我的经验,LinkedList
通常不值得在内存和迭代效率方面付出代价,因此LinkedList
我的默认姿势也不值得。但是在优化热点时,绝对值得交换列表实现以查看是否有所改进。
在Java 9中,您现在可以使用Matcher#results()
获取Stream<MatchResult>
,您可以使用来获取匹配的列表/数组。
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
.matcher("string to search from here")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
// or .collect(Collectors.toList())
Java使正则表达式过于复杂,并且不遵循perl样式。看一下MentaRegex,看看如何在一行Java代码中完成该任务:
String[] matches = match("aa11bb22", "/(\\d+)/g" ); // => ["11", "22"]
这是一个简单的例子:
Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
list.add(m.group());
}
(如果您有更多捕获组,则可以通过它们的索引将它们作为组方法的参数来引用。如果需要一个数组,请使用list.toArray()
)
Pattern.matches()
是静态方法,您不应在Pattern
实例上调用它。Pattern.matches(regex, input)
简直是的简写Pattern.compile(regex).matcher(input).matches()
。
Pattern pattern =
Pattern.compile(console.readLine("%nEnter your regex: "));
Matcher matcher =
pattern.matcher(console.readLine("Enter input string to search: "));
boolean found = false;
while (matcher.find()) {
console.format("I found the text \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
使用结果find
并将其插入group
您的数组/ List /任何位置。
Set<String> keyList = new HashSet();
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher matcher = regex.matcher("Content goes here");
while(matcher.find()) {
keyList.add(matcher.group(1));
}
return keyList;