Java 带有可选子字符串的捕获组
我正在处理以下形式的数据(给出了四个示例,每个示例用新行分隔): 我需要提取出版物名称和发行号(如果存在)。这必须用正则表达式来完成 鉴于上述数据,我希望找到以下结果:Java 带有可选子字符串的捕获组,java,regex,Java,Regex,我正在处理以下形式的数据(给出了四个示例,每个示例用新行分隔): 我需要提取出版物名称和发行号(如果存在)。这必须用正则表达式来完成 鉴于上述数据,我希望找到以下结果: some publication 3 another publication 23 yet another publication <null> here is another publication <null> 关于正则表达式字符串的任何想法都适用于这两
some publication 3
another publication 23
yet another publication <null>
here is another publication <null>
关于正则表达式字符串的任何想法都适用于这两种情况(有和没有发行号)?在可选部分周围使用可选的非捕获组:
(.*?)(?:, issue no\. (\d+))?
^^^ ^^
见
在代码中:
String pattern = "(.*?)(?:, issue no\\. (\\d+))?";
如果希望模式匹配整个字符串,请将其与
Matcher#matches()
一起使用,而不是Matcher#find()
另一种方法-如果问题模式位于字符串的末尾,请尝试首先将其与,\\s*问题\\s*否\\.\\s*(\\d+)“
使用Matcher#find()
,然后,出版物将从启动到匹配开始,发行号将位于第1组:。这很有帮助!今天我了解到,在非捕获组中有捕获组是可能的。
(.*?)(?:, issue no\. (\d+))?
^^^ ^^
String pattern = "(.*?)(?:, issue no\\. (\\d+))?";