简体   繁体   English

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

[英]matching the pattern to a regular expression in java

i am trying to match following pattern 我正在尝试匹配以下模式

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

example to match 匹配的例子

abc/pqrModellmn/xyz
kfkf/flfk/jgf/lflflflMModelkfkfkf/kfkfk

etc. I tried something like 等等,我尝试过类似

Pattern p = Pattern.compile("\D*\\\D*Model\D*\\");
Matcher m =  p.matcher(fileEntry.getAbsolutePath());
System.out.println("The match is:" + m.find()); 
  • \\ is used as escape sequence for Java string literal, so escape it. \\用作Java字符串文字的转义序列,因此请对其进行转义。
  • You should use / , not \\ , to match / . 您应该使用/而不是\\来匹配/

Try this: 尝试这个:

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()); 
    }
}

In regex word is captured by \\w , so I have slightly different regex 在正则表达式中,单词被\\w捕获,所以我的正则表达式略有不同

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

Your final code will look like 您的最终代码如下所示

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