捕获具有可选子字符串的组

时间:2017-03-07 13:18:40

标签: java regex

我正在处理以下表格的数据(给出了四个示例,每个示例用新行分隔):

body {
  background: url('http://www.jqueryscript.net/demo/jQuery-Plugin-To-Create-Auto-Scrolling-Background-AutoBackgroundScroll-js/img/background.jpg') no-repeat left top transparent;
  transition: background-position 5000ms ease-in-out;
}

我需要提取出版物名称,并且 - 如果存在 - 提取问题编号。这必须使用正则表达式完成。

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

以下模式仅适用于具有some publication, issue no. 3 another publication, issue no. 23 yet another publication here is another publication 部分的数据:

some publication            3
another publication         23
yet another publication     <null>
here is another publication <null>

有关正则表达式字符串的任何想法都适用于这两种情况(有和没有问题编号)?

1 个答案:

答案 0 :(得分:4)

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

(.*?)(?:, issue no\. (\d+))?
     ^^^                  ^^ 

请参阅regex demo

在您的代码中:

String pattern = "(.*?)(?:, issue no\\. (\\d+))?";

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