简体   繁体   中英

Regex Pattern matching for an URL

I have a method and input to that is an URL string. I would different types of URL (sample 5 URLs i have mentioned below)

String url1 = "http://domainName/contentid/controller_hscc.jsp?q=1" ;
String url2 = "http://domainName/contentid/controller.jsp?waitage=1" ;
String url3 = "http://domainName/contentid/controller_runner.jsp" ;
String url4 = "http://domainName/contentid/jump.jsp?q=5" ;
String url5 = "http://domainName/contentid/jump.jsp" ;

I need to find if this URL has controller*.jsp pattern in it. If so, I will have to write some other logic for it.

Now, I need to know how to write * controller*.jsp pattern in java

I wrote a regex this way and it returns false always

boolean retVal = Pattern.matches("^(controller)*", url) ;

PS : I use JDK1.4

EDIT-1

I tried below way. Still not woring

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld{

     public static void main(String []args){
        String url = "http://domainName/contentid/controller_hscc.jsp?q=1" ;
        //String url = "baaaaab" ;
        String regex = "/controller(\\w+)?\\.jsp*" ;

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(url);
        System.out.println(m.matches());
     }
}

Match it against the following regex:

controller(\\w+)?\\.jsp

Demo

String re = "controller.+jsp";
String str = "http://domainName/contentid/controller_hscc.jsp?q=1";

Pattern p = Pattern.compile(re);
Matcher m = p.matcher(str);

Try this code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld{

     public static void main(String []args){
        String url = "http://domainName/contentid/controller_hscc.jsp?q=1" ;
        //String url = "baaaaab" ;
        String regex = "^.*?controller(\\w+)?\\.jsp.*?$" ;

        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(url);
        boolean retVal = Pattern.matches(regex, url) ;
        System.out.println(m.matches() + "__" + retVal);
     }
}

I found this working fine:

(controller.*\.jsp(\?.*)?)

see here .

As a java string, it should be "(controller.*\\\\.jsp(\\\\?.*)?)"

Moreover, it will give you two groups: the whole one and the part after the ? .

You could also do it by splitting the url by / s, taking the last part and checking if that starts with controller - without using any regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM