Java regex behaving wierd

Tay

New Member
#1
I have the below test case,
Mã:
    @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));
    }
The Util method is:
Mã:
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;
    }
Can someone please help, why the regex Sample*.*Selection*.*Preliminary matches the fileName = Sample selectiossn preliminary ?

This test case should pass, but it fails because of the first assert. :S
 

Admin

Administrator
Thành viên BQT
#2
The * in regex means 0 or more of the previous character, while . means any single character.

What your expression is looking for is:

  1. Exactly Sampl
  2. 0 or more e
  3. 0 or more of any char
  4. Exactly Selectio
  5. 0 or more n
  6. 0 or more of any char And so on
The problem would fall under points 5 and 6:

No n was found under point 5, and ssn would match point 6
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top