Monday, January 5, 2015

Extract text from a string using Java regular expression

In the example below, you can extract the URL path from a complete URL:

String regex = "\\A(http://|https://)(.[^/]*)(.+)";
String url = "http://example.com/portal/194/174120/products/1413876472.8028_14_o.jpg";
Matcher matcher = Pattern.compile(regex).matcher(url);
if (matcher.find()) {
 String contextPath = matcher.group(3);
 return contextPath;
}

and the result is:

/portal/194/174120/products/1413876472.8028_14_o.jpg



Reference:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

No comments:

Post a Comment