开发者

Match url with the pattern

开发者 https://www.devze.com 2023-04-03 03:52 出处:网络
I am opening a filters.txt file. Below is the file: http://www.somehost.com/.*/releases, RE,TO I am comparing the first entry in the text file with the hard coded url in my code. Any URL that start

I am opening a filters.txt file. Below is the file:

http://www.somehost.com/.*/releases, RE,TO

I am comparing the first entry in the text file with the hard coded url in my code. Any URL that starts with the pattern(firstentry) in the text file should do this in particular if loop. Here this url http://www.somehost.com/news/releases/2011/09/07/somehost-开发者_如何学Cand-life-care-networks-launch-3g-mobile-health-project-help-patien is originated from this pattern url only http://www.somehost.com/.*/releases. But still it is not matching this pattern. Any suggestions why is it happening?

BufferedReader readbuffer = null;
            try {
                readbuffer = new BufferedReader(new FileReader("filters.txt"));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            String strRead;



        try {
            while ((strRead=readbuffer.readLine())!=null){
                String splitarray[] = strRead.split(",");
                String firstentry = splitarray[0];
                String secondentry = splitarray[1];
                String thirdentry = splitarray[2];



                Pattern p = Pattern.compile("^" +firstentry);
                Matcher m = p.matcher("http://www.somehost.com/news/releases/2011/09/07/somehost-and-life-care-networks-launch-3g-mobile-health-project-help-patien");

                if (m.find() && thirdentry.startsWith("LO")) {
                  //Do whatever

                    System.out.println("First Loop");

                }

                else if(m.find() && thirdentry.startsWith("TO"))
                {
                    System.out.println("Second Loop");
                }

                }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 


Try seperating the find() and your if/else. You need to call the find() only once in your for loop.

Javadoc says: Matcher.find() Attempts to find the next subsequence of the input sequence that matches the pattern. Next is quite important, it means it skips to the next possible match every time you call the method.

boolean found = m.find();
if (found && thirdentry.startsWith("LO")) {
//Do whatever
  System.out.println("First Loop");
}
else if(found && thirdentry.startsWith("TO"))
{
  System.out.println("Second Loop");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消