Arun
Arun

Reputation: 3680

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

Upvotes: 2

Views: 4120

Answers (4)

Sufian Latif
Sufian Latif

Reputation: 13356

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.

Upvotes: 1

Andynedine
Andynedine

Reputation: 441

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

Upvotes: 1

Sirius_Black
Sirius_Black

Reputation: 471

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

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

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

Match it against the following regex:

controller(\w+)?\.jsp

Demo

Upvotes: 2

Related Questions