Vik
Vik

Reputation: 9289

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

Upvotes: 0

Views: 40

Answers (2)

Saleem
Saleem

Reputation: 8978

In regex word is captured by \w, so I have slightly different regex

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

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

  • \ is used as escape sequence for Java string literal, so escape it.
  • 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()); 
    }
}

Upvotes: 2

Related Questions