[英]matching the pattern to a regular expression in java
我正在嘗試匹配以下模式
(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());
\\
用作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());
}
}
在正則表達式中,單詞被\\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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.