java - 任何以模式开头的 url.. 执行此操作

标签 java regex pattern-matching

我想将 url A (http://www.somehost.com/citizenship) 与模式 url B (http://www.somehost.com/*) 进行比较,如果 URL A 以模式 url B 开头,则执行此操作.. 由于 URL 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();
        }

最佳答案

String.startsWith(String) 有什么问题吗? ?

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

或者我是否错过了您想要实现的目标?

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

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

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

关于java - 任何以模式开头的 url.. 执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290142/

相关文章:

java - java :comp/env/HRONLINEFSDEV2 JNDI name could not be instantiated in Liberty 引用的对象

Python 正则表达式小时到分钟

Javascript - 匹配一个长 5 位数字的正则表达式

c++ - 哪个是更好的字符串搜索算法? Boyer-Moore 还是 Boyer Moore Horspool?

java - 输入流关闭和 Sonar 问题

java - 如何从 .jar 创建 .exe

Java 排序不正确

regex - 正则表达式中英镑 (#) 的含义

regex - 我可以在 HTML5 模式属性中使用包含 & 符号的正则表达式吗?

java - 为什么这段代码不能正常工作?