Java support for conditional lookahead

旧城冷巷雨未停 提交于 2019-11-29 14:32:34

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));

OUTPUT:

Macthed: [11111]
Macthed: [22222]
Macthed: [44444-4444]

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.

The reason why your original RegEx is throwing exception because there is a syntax error in ?:(?=-) part of your RegEx.

You'r missing a colon after (?, i.e. use this regex (non-Java-String): \d{5}(?:(?=-)-\d{4}).

However, this might still not produce the result you want. Please post some example input and required output.

Your question is a little unclear to me. I suppose you are looking for:

String st = "11111 22222 33333- 44444-4444";
String pattern = "\\d+(- )";
String res  = st.replaceAll(pattern,"");
System.out.println(res);

Output = 11111 22222 44444-4444

Kleenestar
(\d{5}(?!-\s)(?:-\d{4})?)

hence:

String regex = "(\\d{5}(?!-\\s)(?:-\\d{4})?)";`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!