关于#java#的问题:正则表达式


public static void main(String[] args) {
        String str = "是我的";
        String pattern = "我的$";
        boolean matches = str.matches(pattern);
        System.out.println(matches);
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        System.out.println(m.matches());
    }

各位帮忙看看,这个表达式为什么会返回false!!

img

matcher()匹配的是整个字符串,源字符串是3个字,你这里只有两个,改成下面这样试试:

    public static void main(String[] args) {
        String str = "是我的";
        String pattern = ".*\\u6211\\u7684$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        System.out.println(m.matches());
    }

正则表达式的字面量字符串中不需要使用"/g"标志,因为这个标志是在JavaScript中使用的,在Java中不需要使用。
代码中的正则表达式错误,因为它使用了错误的转义字符("/\u6211\u7684$/g")。正确的正则表达式应该是"^是我的$",表示仅匹配字符串"是我的"。