如何提取与特定关键字后的模式匹配的多个值?

问题描述 投票:0回答:1

需要有关如何使用正则表达式提取护照关键字后匹配的多个护照号码的帮助

文字:

   my friends passport numbers are V123456, V123457 and V123458

正则表达式: (?<=passport)\s*(?:\w+\s){0,10}\s*(\b[a-zA-Z]{0,2}\d{6,12}[a-zA-Z]{0,2}\b)

预期匹配输出:

V123456

V123457

V123458

实际产量: V123456

java regex regex-lookarounds regex-group regexp-replace
1个回答
0
投票

这里不能依赖lookbehind,因为你需要一个无限长度的模式。它受支持,但仅在最近的 Java 版本中。

您可以使用基于

\G
运算符的模式:

(?:\G(?!\A)|\bpassport\b).*?\b([a-zA-Z]{0,2}\d{6,12}[a-zA-Z]{0,2})\b

请参阅 正则表达式演示

请参阅下面的 Java 演示

String s = "my friends passport numbers are V123456, V123457 and V123458";
String rx = "(?:\\G(?!^)|\\bpassport\\b).*?\\b([a-zA-Z]{0,2}\\d{6,12}[a-zA-Z]{0,2})\\b";
Pattern pattern = Pattern.compile(rx, Pattern.DOTALL);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1)); 
}

输出:

V123456
V123457
V123458
© www.soinside.com 2019 - 2024. All rights reserved.