繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM