如何在Java中仅找到完全匹配的模式?

时间:2019-05-24 16:38:14

标签: java regex string regex-lookarounds regex-group

字符串“ description”具有5位,7位子字符串。我只想分别匹配5digit,7digit和5digit,7digit。但是,5位数子字符串会提取整个5位数字符串和7位数的前5位数。

Pattern 5digitPattern = Pattern.compile("([0-9]{5})");
Pattern 7digitPattern = Pattern.compile("([0-9]{7})");

Matcher 5digitMatcher = 5digitPattern.matcher(description);
Matcher 7digitMatcher = 7digitPattern.matcher(description);

            if (5digitMatcher.find()) {
                for (int i = 0; i < 5digitMatcher.groupCount(); i++) {
                    System.out.print("\t" + 5digitMatcher.group(i));
                }
            }

            if (7digitMatcher.find()) {
                for (int i = 0; i < 7digitMatcher.groupCount(); i++) {
                    System.out.print("\t" + 7digitMatcher.group(i));
                }
            }

请帮助我分别将5位,7位与5位,7位匹配。

1 个答案:

答案 0 :(得分:2)

使用单词边界:

Pattern 5digitPattern = Pattern.compile("\\b([0-9]{5})\\b");
Pattern 7digitPattern = Pattern.compile("\\b([0-9]{7})\\b");

根据注释,如果要匹配abc12345def中的数字,请使用否定性环视:

Pattern 5digitPattern = Pattern.compile("(?<![0-9])([0-9]{5})(?![0-9])");
Pattern 7digitPattern = Pattern.compile("(?<![0-9])([0-9]{7})(?![0-9])");