首页 > 解决方案 > Java 正则表达式表现怪异

问题描述

我有以下测试用例,

    @Test
    public void test_check_pattern_match_caseInSensitive_for_pre_sampling_filename() {
        // given
        String pattern = "Sample*.*Selection*.*Preliminary";

        // when

        // then
        assertThat(Util.checkPatternMatchCaseInSensitive(pattern, "Sample selectiossn preliminary"), is(false));
        assertThat(Util.checkPatternMatchCaseInSensitive(pattern, "sample selection preliminary"), is(true));
    }

Util 方法是:

public static boolean checkPatternMatchCaseInSensitive(String pattern, String value) {

        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(value);
        if (matcher.find())
            return true;

        return false;
    }

有人可以帮忙吗,为什么正则表达式Sample*.*Selection*.*Preliminary匹配 fileName = Sample selectiossn preliminary

这个测试用例应该通过,但由于第一个断言而失败。:S

标签: javaregex

解决方案


in 正则表达式表示前一个字符的*0 个或多个,而.表示任何单个字符。

你的表达正在寻找的是:

  1. 确切地Sampl
  2. 0个或更多e
  3. 0 个或多个任意字符
  4. 确切地Selectio
  5. 0个或更多n
  6. 0个或更多任何字符等等

问题属于第 5 点和第 6 点:

在第 5 点下没有n找到,ssn与第 6 点匹配


推荐阅读