【问题标题】:Positive Lookbehind with commas separated list带有逗号分隔列表的正向 Lookbehind
【发布时间】:2018-05-30 18:21:08
【问题描述】:

我是一名 Java 开发人员,我是 Regex 的新手,我遇到了与 here in Stackoverflow 类似的问题。我有 2 个问题,

  • SKIP 在 Java 中不起作用
  • 我开始按照Regex link 采用第二种方法,但我的用例如下,

如果我有一个类似的字符串,

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

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

我卡在这里,请帮忙。

【问题讨论】:

    标签: java regex lookbehind negative-lookahead


    【解决方案1】:

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

    但是,此正则表达式将使用 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));
    

    【讨论】:

    • 我还有一个问题It is very nice in summer and in summer time we swim, run, tan, or walk, talk 有没有办法提取 [swim, run, tan, walk, talk] 。感谢您的帮助。
    • @Krishna 是的。尝试学习正则表达式,看看您是否可以修改上面的正则表达式,而不是要求我们为您编写代码。
    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2021-05-18
    相关资源
    最近更新 更多