Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用模式匹配器正则表达式类_Java_Regex_Tokenize_Scjp - Fatal编程技术网

Java 使用模式匹配器正则表达式类

Java 使用模式匹配器正则表达式类,java,regex,tokenize,scjp,Java,Regex,Tokenize,Scjp,在以下示例中: class ZiggyTest2{ public static void main(String[] args){ Pattern p = Pattern.compile("Water water WATER everywhere"); Matcher m = p.matcher("water"); while(m.find()){ System.o

在以下示例中:

class ZiggyTest2{  
        public static void main(String[] args){  

            Pattern p = Pattern.compile("Water water WATER everywhere");
            Matcher m = p.matcher("water");

            while(m.find()){
                System.out.println(m.start() + " " + m.group());
            }

            System.out.println("[Done]");
        }    
    }  

m.find()方法总是false,因此它找不到字符串“water”。这是什么原因?

您已反转字符串:

  • Pattern
    编译正则表达式
  • Matcher
    应用于输入
你应该:

        Pattern p = Pattern.compile("water");
        Matcher m = p.matcher("Water water WATER everywhere");
还请注意,如果要进行不区分大小写的匹配,则需要使用以下任一选项初始化模式:

        Pattern p = Pattern.compile("water", Pattern.CASE_INSENSITIVE);
        // or:
        Pattern p = Pattern.compile("(?i)water");