可选的子捕获组

Abd*_*ull 5 java regex

我正在与以下形式的数据工作(四个例子给出的,每个分离的由一个新行):

some publication, issue no. 3
another publication, issue no. 23
yet another publication
here is another publication
Run Code Online (Sandbox Code Playgroud)

我需要提取的出版物名称和 - 的情况下,它的存在 - 的发行数量。这必须用正则表达式来完成。

因此,鉴于上述数据,我正在寻找以下结果:

some publication            3
another publication         23
yet another publication     <null>
here is another publication <null>
Run Code Online (Sandbox Code Playgroud)

下面的模式只适用于具有数据, issue no. xyz部分:

    String underTest = "some publication, issue no. 3";

    String pattern = "(.*?), issue no. (\\d+)";
    Matcher matcher = Pattern.compile(pattern).matcher(underTest);

    boolean found = matcher.find();
    if (found) {
        log.info("something found");
        String group1 = matcher.group(1);
        log.info("group1: {}", group1);

        String group2 = matcher.group(2);
        log.info("group2: {}", group2);
    }
Run Code Online (Sandbox Code Playgroud)

任何想法的正则表达式的字符串,这两种情况下工作(有和无的问题数)?

Wik*_*żew 4

在可选部分周围使用可选的非捕获组:

(.*?)(?:, issue no\. (\d+))?
     ^^^                  ^^ 
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

在你的代码中:

String pattern = "(.*?)(?:, issue no\\. (\\d+))?";
Run Code Online (Sandbox Code Playgroud)

如果您希望模式匹配整个字符串,请使用 with 而Matcher#matches()不是Matcher#find()。