你可以做这样的事情:
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static List<String> getAllMatches(String text, String regex) {
List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text);
while(m.find()) {
matches.add(m.group(1));
}
return matches;
}
public static void main(String[] args) {
System.out.println(getAllMatches("abaca", "a.a"));
System.out.println(getAllMatches("abaa", "a.*a"));
}
}
哪些打印:
[aba, aca]
[abaa, aa]
唯一的问题是你从最后的比赛列表中消失了。这是因为 贪婪 在 .您无法使用正则表达式解决此问题。您可以通过迭代所有可能的子字符串并调用每个子字符串来执行此操作:aba
.*
a.*a
.matches(regex)
public static List<String> getAllMatches(String text, String regex) {
List<String> matches = new ArrayList<String>();
for(int length = 1; length <= text.length(); length++) {
for(int index = 0; index <= text.length()-length; index++) {
String sub = text.substring(index, index + length);
if(sub.matches(regex)) {
matches.add(sub);
}
}
}
return matches;
}
如果文本保持相对较小,这将起作用,但对于较大的字符串,这可能会变得计算量过大。