正则表达式:匹配除以 abc 开头的所有 7 位数字
Regex : matches all 7 digit number except the one that starts with abc
例如:
abc:1234567,cd:2345678,efg:3456789012
预期结果
2345678
我试过了
(?!abc)\d{7,7}
我的结果:1234567
您可以使用
\b(?<!abc:)\d{7}\b
(?<!\d)(?<!abc:)\d{7}(?!\d)
参见regex demo。
详情:
\b
- 字边界((?<!\d)
确保当前位置左侧没有其他数字)
(?<!abc:)
- 如果在当前位置 的左侧紧邻 abc:
,则匹配失败的否定后视
\d{7}
- 七位数
\b
- 字边界((?!\d)
确保当前位置右侧没有其他数字)。
参见Java demo:
String s = "abc:1234567,cd:2345678,efg:3456789012";
Pattern pattern = Pattern.compile("\b(?<!abc:)\d{7}\b");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group()); // => 2345678
}
例如: abc:1234567,cd:2345678,efg:3456789012
预期结果 2345678
我试过了
(?!abc)\d{7,7}
我的结果:1234567
您可以使用
\b(?<!abc:)\d{7}\b
(?<!\d)(?<!abc:)\d{7}(?!\d)
参见regex demo。
详情:
\b
- 字边界((?<!\d)
确保当前位置左侧没有其他数字)(?<!abc:)
- 如果在当前位置 的左侧紧邻 \d{7}
- 七位数\b
- 字边界((?!\d)
确保当前位置右侧没有其他数字)。
abc:
,则匹配失败的否定后视
参见Java demo:
String s = "abc:1234567,cd:2345678,efg:3456789012";
Pattern pattern = Pattern.compile("\b(?<!abc:)\d{7}\b");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group()); // => 2345678
}