Monday, September 17, 2007

Using java regular expressions to match groups

It's been demonstrated over and over again, but I always seem to forget the "simple example". So here it is:


import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
/*
*Going to match a URL that looks like this
* /url/prefix/--sitename--/menu.--menuid--/?param=--itemid--
* and change it into
* /url/prefix/--sitename--/--menuname--/--itemname--
*/
String expr="(/url/prefix/[a-zA-Z0-9_-]+)/menu\\.([a-zA-Z0-9_-]+)/\\?param=([a-zA-Z0-9_-]+)";
Pattern p = Pattern.compile(expr);
Matcher m = p.matcher(uri);
if ( m.matches() ) {
prefix= m.group(1);
menuitem = m.group(2);
guid = m.group(3);
if ( guid != null && prefix != null && menuitem != null ) {
uribuilder.append(prefix);
uribuilder.append("/");
uribuilder.append(getMenuName(menuitem));
uribuilder.append("/");
uribuilder.append(getItemName(guid));
uri=uribuilder.toString();
}
}

No comments:

Post a Comment

[Due to much spam, comments are now moderated and will be posted after review]

Note: Only a member of this blog may post a comment.