extract substring from within 2 tokens

22 views
Skip to first unread message

pieceovcake

unread,
Dec 14, 2010, 4:24:05 PM12/14/10
to google-we...@googlegroups.com
anyone know the equivalent of

String description = "ID:89790797:ID";
String foundid = org.apache.commons.lang.StringUtils.substringBetween(description, "ID:", ":ID");

in the java.util.regex library?

I need to extract the string between the ID tags

Thanks
                

zixzigma

unread,
Dec 14, 2010, 4:33:21 PM12/14/10
to Google Web Toolkit
split the string (eg.description), and use ":" as delimiter,


String [] result = description.split(":"); //result is an array of 3
elements "ID" "89790797" "ID"
String id = result[1];


zixzigma

unread,
Dec 14, 2010, 4:43:11 PM12/14/10
to Google Web Toolkit

Thomas Broyer

unread,
Dec 15, 2010, 6:34:13 AM12/15/10
to google-we...@googlegroups.com
First, java.util.regex is not emulated in GWT, so there's no reason to replace Apache Commons with java Regex.

There's however a com.google.gwt.regexp module. You could use something like:

RegExp r = RegExp.compile("ID:(.*?):ID", "g");
MatchResult m = r.exec(description);
if (m != null) {
   foundid = m.getGroup(1);
} else {
   // not found
}

(assuming 'description' can contain many things around the ID:...:ID, otherwise the String.split() option, or even String.substring, possibly combined with String.startsWith and String.endsWith, is the way to go as it's less error-prone)
Reply all
Reply to author
Forward
0 new messages