我正在尝试匹配以下模式
(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());
答案 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());
}