任何以模式开头的网址都会这样做

时间:2011-09-02 23:27:48

标签: java regex pattern-matching

我想将网址A(http://www.somehost.com/citizenship)与模式网址B(http://www.somehost.com/*)进行比较,如果网址A以模式网址B开头,则执行此操作。由于网址A已生成从URL B ..所以任何以这种模式开头的url ..只是在if循环中做这件事......任何建议都将受到赞赏...... !!

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];
                //String fourthentry = splitarray[3];
                //String fifthentry = splitarray[4];
                System.out.println(firstentry + " " + secondentry+ " " +thirdentry);
                URL url1 = new URL("http://www.somehost.com/citizenship");

 //Any url that starts with this pattern then do whatever you want in the if loop... How can we implement this??                    
                Pattern p = Pattern.compile("http://www.somehost.com/*");

                Matcher m = p.matcher(url1.toString());

                if (m.matches()) {
                  //Do whatever
                    System.out.println("Yes Done");
                }



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

2 个答案:

答案 0 :(得分:1)

String.startsWith(String)出了什么问题?

你可以像这样调用它:url1.toString().startsWith("http://www.somehost.com/")

或者我是否想念你正在努力实现的目标?

无论如何,这是要构建的正则表达式:http://www\.somehost\.com/.*

您需要学习正则表达式语法,其中“。”表示任何字符,因此您需要在“www”和“somehost”之间转义它。

在Java代码中,您还需要转义退格,因此它变为:Pattern.compile("http://www\\.somehost\\.com/.*");

答案 1 :(得分:0)

我相信这应该可以解决问题:

    private final static String regexPattern = "http://www.somehost.com/[0-9a-zA-Z\\-]*/wireless-reach(/[0-9a-zA-Z\\-]*)*";
    String pattern = "http://www.somehost.com/citizen-ship/wireless-reach/fil1";

    if(pattern.matches(regex))
         System.out.println("Matched!");