使用complie和regex获取字符串中的所有匹配项

时间:2017-04-05 19:33:29

标签: java regex

我试图获取所有以_开头并以=结尾的匹配,其中的网址类似于

?_field1=param1,param2,paramX&_field2=param1,param2,paramX

在这种情况下,我正在寻找_fieldX=

的任何实例

我用来获取它的方法看起来像

public static List<String> getAllMatches(String url, String regex) {
    List<String> matches = new ArrayList<String>();
    Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(url);
    while(m.find()) {
        matches.add(m.group(1));
    }
    return matches;
}

称为

List<String> fieldsList = getAllMatches(url, "_.=");

但不知何故找不到我所期望的任何东西。

我错过了哪些建议?

2 个答案:

答案 0 :(得分:1)

由于您正在将正则表达式传递给该方法,因此您似乎需要一个通用函数。

如果是这样,您可以使用此方法:

public static List<String> getAllMatches(String url, String start, String end) {
    List<String> matches = new ArrayList<String>();
    Matcher m = Pattern.compile(start + "(.*?)" + end).matcher(url);
    while(m.find()) {
        matches.add(m.group(1));
    }
    return matches;
}

并将其命名为:

List<String> fieldsList = getAllMatches(url, "_", "=");

答案 1 :(得分:1)

(?=(_.=))这样的正则表达式匹配所有以_开头的重叠匹配,然后有任何1个字符(除了换行符),然后是=

在您提供的字符串的上下文中不需要重叠匹配。

您可以使用惰性点匹配模式_(.*?)=。或者,您可以使用基于否定字符类的正则表达式:_([^=]+)=(它将捕获除=符号以外的任何一个或多个字符组。)

相关问题