Prasanna
- All
- Personal
- Sports
- Sun
- Tech
- Useful Code
Monday Aug 27, 2007
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!
Posted at 10:53PM Aug 27, 2007 by prasanna in Useful Code | Comments[1]


ghj
Posted by 200.217.214.66 on August 28, 2007 at 12:49 AM IST #