Snippet: Fetching a regular expression

I'm including a small handy snippet to use regular expressions in your Java code.

Regular expressions allow to save time when in need of retrieving a very specific portion of text within a string. On this case, I've used to gather text from an HTML page.
* Gets a string value from laptop characteristics based on a given pattern.
* A Matcher object is used internally.
* @param source string containing the text to be parsed
* @param reg regular expression pattern to use
* @param group index of one of the groups found by the pattern
* @return String containing the found pattern, or null otherwise
private String findRegEx(String source, String reg, int group) {
String out = null;

Pattern p = Pattern.compile(reg); // Prepare the search pattern.
Matcher matcher = p.matcher(source); // Retrieve our items.

if (matcher.find()) {
try {
out =;
} catch (Exception e) {}

return out;

You can use a regular expression simulator as the one available at to test your regular expressions and also change the available templates over there.


No comments:

Post a Comment