以逗号分隔列表的正面回顾

Positive Lookbehind with commas separated list

我是一名 Java 开发人员,我是正则表达式的新手,我遇到了与 here in Whosebug 类似的问题。我有 2 个问题,

如果我有这样的字符串,

It is very nice in summer and in summer time we swim, run, tan

它应该基于 Positive lookbehind 提取,"summer time we",它应该提取,[smim, 运行, tan] 作为一个数组。

我卡在这里了,请帮忙。

在 Java 中,正则表达式本身不能 return 数组。

但是,这个正则表达式将 return 使用 find() 循环得到你想要的值:

(?<=summer time we |\G(?<!^), )\w+

它与您提到的 second answer 几乎相同。

在 Java 9+ 中,您可以这样创建数组:

String s = "It is very nice in summer and in summer time we swim, run, tan";
String[] results = Pattern.compile("(?<=summer time we |\G(?<!^), )\w+")
                          .matcher(s).results().map(MatchResult::group)
                          .toArray(i -> new String[i]);
System.out.println(Arrays.toString(results));

输出

[swim, run, tan]

在 Java 5+ 中,您可以使用 find() 循环来完成:

String s = "It is very nice in summer and in summer time we swim, run, tan";
List<String> resultList = new ArrayList<String>();
Pattern regex = Pattern.compile("(?<=summer time we |\G(?<!^), )\w+");
for (Matcher m = regex.matcher(s); m.find(); )
    resultList.add(m.group());
String[] results = resultList.toArray(new String[resultList.size()]);
System.out.println(Arrays.toString(results));