Java支持条件超前 [英] Java support for conditional lookahead
问题描述
在下面,让我说邮政编码,我试图从结果中排除33333-
.
我愿意:
In the following let's say zip codes I am trying to exclude the 33333-
from the result.
I do:
String zip = "11111 22222 33333- 44444-4444";
String regex = "\\d{5}(?(?=-)-\\d{4})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(zip);
while (matcher.find()) {
System.out.println(" Found: " + matcher.group());
}
期望得到:
Found: 11111
Found: 22222
Found: 44444-4444
我正在尝试强制采用以下格式:
5位数字(可选),后跟-和4位数字.不需要只带有-(连字符)的5位数字
I am trying to enforce format of:
5 digits optionally followed by a - and 4 digits. 5 digits with just a - (hyphen) is not wanted
我得到异常:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unknown inline modifier near index 7
\d{5}(?(?=-)(-\d{4}))
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.group0(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
我没有正确使用条件超前吗?
Am I not using the conditional lookahead correctly?
推荐答案
要捕获除33333以外的所有数字,请使用以下代码:
To capture all numbers except 33333 use this code:
String zip = "11111 22222 33333- 44444-4444";
String regex = "\\d{5}(?=(-\\d{4}|\\s|$))(-\\d{4})?";
Matcher m = Pattern.compile(regex).matcher(zip);
while(m.find())
System.out.printf("Macthed: [%s]%n", m.group(1));
输出:
Macthed: [11111]
Macthed: [22222]
Macthed: [44444-4444]
说明::此RegEx使用的前瞻性本身就像一个条件,这意味着匹配5位数字,必须跟-和4位数字或空格或字符串末尾,然后是(可选)匹配文本和4位数字.
Explanation: This RegEx is using lookahead that itself is like a condition, which means match 5 digit number which must be followed by - and 4 digits OR a space OR end of string and then it is optionally matching a text - and 4 digits.
原始RegEx之所以抛出异常是因为RegEx的?:(?=-)
部分存在语法错误.
The reason why your original RegEx is throwing exception because there is a syntax error in ?:(?=-)
part of your RegEx.
这篇关于Java支持条件超前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!