首页 > 解决方案 > 带有逗号分隔列表的正向 Lookbehind

问题描述

我是一名 Java 开发人员,而且我是 Regex 的新手,我在 Stackoverflow 中遇到了类似的问题。我有2个问题,

如果我有一个字符串,

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

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

我被困在这里,请帮助。

标签: javaregexlookbehindnegative-lookahead

解决方案


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

但是,这个正则表达式将使用find()循环返回您想要的值:

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

它与您提到的第二个答案几乎相同。

在 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));

推荐阅读