When you use java regular-expression pattern.matcher (), the source does not match regex. But, my result of hope is, source matches regex

advertisements

When use java regular-expression pattern.matcher(), source does not match regex.But, my hope result is ,source matches regex.

  • String source = "ONE.TWO"
  • String regex = "^ONE\\.TWO\\..*"
    import java.util.regex.Pattern;

    public class Test {
        public static void main(String[] args) {
            test();
        }

        public static void test() {
            Test stringDemo = new Test();
            stringDemo.testMatcher();
        }

        public void testMatcher() {
            String source = "ONE.TWO";
            String regex = "^ONE\\.TWo\\..*";
            // The result = false, "not match". But, the hope result is true, "match"
            matcher(source, regex);
        }

        public void matcher(String source, String regex) {
            Pattern pattern = Pattern.compile(regex);

            boolean match = pattern.matcher(source).matches();
            if (match) {
                System.out.println("match");
            } else {
                System.out.println("not match");
            }
        }
    }

In your code, your regular expression expects the o in TWO to be lower case and expects it to be followed by a ..

Try:

String source = "ONE.TWo.";

This will match your regular expression as coded in your question.

The expression \. means match a literal dot (rather than any character). When you code this into a Java String, you have to escape the backslash with another backslash, so it becomes "\\.".

The .* on the end of the expression means "match zero or more of any character (except line-break)".

So this would also match:

String source = "ONE.TWo.blah blah";