Monday, March 06, 2006

Use Regular Expression to retrieve a substring

Use regular expressions to retrieve a substring, the match ([{}:x0-9a-f]*) below retrieves any substring of characters matching the any greedy match of characters within the square brackets...

String search = "The beginning part this is the substring which should be retrieved and here is the end part";
Pattern pattern = Pattern.compile("The beginning part ([x0-9a-f]*) and here is the end part");
Matcher match= pattern.matcher(search);
String result = "nothing":

if (match.matches()){
result = match.group(1);
}
else{
return null;
}

System.out.println("Result of the match: " + result);

OUTPUT: Result of the match: this is the substring which should be retrieved


No comments: