将模式匹配到java中的正则表达式

时间:2016-03-13 03:14:37

标签: java regex

我正在尝试匹配以下模式

(any word string)/(any word string)Model(any word string)/(any word string)

匹配

的示例
abc/pqrModellmn/xyz
kfkf/flfk/jgf/lflflflMModelkfkfkf/kfkfk

等。 我试过像

这样的东西
Pattern p = Pattern.compile("\D*\\\D*Model\D*\\");
Matcher m =  p.matcher(fileEntry.getAbsolutePath());
System.out.println("The match is:" + m.find()); 

2 个答案:

答案 0 :(得分:2)

  • \用作Java字符串文字的转义序列,因此请将其转义。
  • 您应该使用/而不是\来匹配/

试试这个:

import java.util.regex.*;
class Test {
    static class Hoge {
        public String getAbsolutePath() {
            return "abc/pqrModellmn/xyz";
            //return "kfkf/flfk/jgf/lflflflMModelkfkfkf/kfkfk";
        }
    }
    public static void main(String[] args) throws Exception {
        Hoge fileEntry = new Hoge();

        Pattern p = Pattern.compile("\\D*/\\D*Model\\D*/\\D*");
        Matcher m =  p.matcher(fileEntry.getAbsolutePath());
        System.out.println("The match is:" + m.find()); 
    }
}

答案 1 :(得分:0)

在正则表达式中,\w捕获了单词,因此我的正则表达式略有不同

\w+/\w+Model\w+/\w+

您的最终代码将如下所示

public static void main(String[] args) {

    String rx = "\\w+/\\w+Model\\w+/\\w+";

    Pattern p = Pattern.compile(rx);
    Matcher m =  p.matcher(fileEntry.getAbsolutePath());

    System.out.println("The match is:" + m.find());
}