Java Regular Expressions: Validating HTTP GET URIs, fetching GET Paramaters and values

I was wondering if there is a way to check the validity of HTTP GET URI using Java regular expressions and if its valid, it should fetch all the GET Parameters and their values. Fortunately after some time hacking around Java REs, I discovered an easy solution to accomplish the same, though I am not sure if its efficient.

class URIMatcher {
public static void main (String args[]) {
   
    String query = "Param1=1&Param2=23&Param3=3335&Param4=hello&Param5=&Param6=world";
   
    Pattern ValidURI = Pattern.compile("(?:([a-zA-Z0-9]+)=([\^=&]\*)&)\*([a-zA-Z0-9]+)=([\^=&]\*)");
    Pattern getValues = Pattern.compile("([a-zA-Z0-9]+)=([\^=&]\*)&\*");
    Matcher ValidURIMatch = ValidURI.matcher(query);
    Matcher getParams = getValues.matcher(query);
   
    if (ValidURIMatch.matches()) {
        while(getParams.find())
            System.out.println("Name = " + getParams.group(1) + " Value = " + getParams.group(2));       
    } else {
        System.out.println("URI is not valid");
    }   
 }
}

The first pattern accepts a valid URI (URIs like Param1=&, Param1=hello&Param2, etc are invalid and are filtered out). From the valid URI, the second pattern fetches all GET Parameters and their values, for the above example it will be

Name = Param1 Value = 1
Name = Param2 Value = 23
Name = Param3 Value = 3335
Name = Param4 Value = hello
Name = Param5 Value =
Name = Param6 Value = world

Regular Expressions are really powerful indeed!
Comments:

ghj

Posted by guest on August 27, 2007 at 05:49 PM IST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

prasanna

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today