将url与模式匹配

时间:2011-09-07 22:14:11

标签: java regex pattern-matching

我正在打开filters.txt文件。以下是文件:

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

我正在将文本文件中的第一个条目与我的代码中的硬编码网址进行比较。任何以文本文件中的模式(firstentry)开头的URL都应该特别是在循环中执行此操作。此处此网址http://www.somehost.com/news/releases/2011/09/07/somehost-and-life-care-networks-launch-3g-mobile-health-project-help-patien仅来自此模式网址http://www.somehost.com/.*/releases。但它仍然不符合这种模式。任何建议为什么会发生?

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

1 个答案:

答案 0 :(得分:0)

尝试分隔find()和你的if / else。您只需在for循环中调用find()一次。

Javadoc说:   Matcher.find() Attempts to find the next subsequence of the input sequence that matches the pattern.接下来非常重要,这意味着每次调用方法时它都跳到下一个可能的匹配。

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