鉴于以下情况:
"John Smith"
"John Smith (123)"
"John Smith (123) (456)"
我想捕捉:
"John Smith"
"John Smith", "123"
"John Smith (123)", "456"
什么样的 Java 正则表达式可以让我做到这一点?
我试过了(.+)\s\((\d+)\)$
它适用于“John Smith (123)”和“John Smith (123) (456)”,但不适用于“John Smith”。如何更改正则表达式以适用于第一个输入?
你可以转第一个.+
懒惰,并用非捕获可选组包装后面的部分:
(.+?)(?:\s\((\d+)\))?$
^ ^^^ ^^
See the 正则表达式演示 https://regex101.com/r/hI0eS1/1
实际上,如果您使用正则表达式String#matches()
最后$
是多余的。
Details:
-
(.+?)
- 第 1 组捕获除换行符之外的一个或零个字符,尽可能少(因此,允许后续子模式“落入”一个组中)
-
(?:\s\((\d+)\))?
- 可选的空白序列,(
,第 2 组捕获 1+ 位数字和)
-
$
- 绳锚的末端。
A Java演示 http://ideone.com/2mXjTZ:
String[] lst = new String[] {"John Smith","John Smith (123)","John Smith (123) (456)"};
Pattern p = Pattern.compile("(.+?)(?:\\s\\((\\d+)\\))?");
for (String s: lst) {
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
if (m.group(2) != null)
System.out.println(m.group(2));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)