Pages

Thursday 28 April 2011

Regular Expressions in Android

If you are not familiar with regular expressions, then it is well worth spending some time finding out about them. Basically a regular expressions allow you to define a and search for a pattern of text within a string, to pick out an email address for example. Head over to regular-expressions.info and find out more, it may seem overly complicated at first, but you will often find you cannot do without them. There are also plenty of sites for testing patterns against, regexpal.com is a good simple one.

Right, let's get to the code. To handle regular expressions in Android you use the standard Java classes, so if you are familiar with these then there is nothing more to learn. Otherwise, the first thing to do is add the following import references to your class:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

My example method will match a defined pattern in the variable myString. If a match is found then the first match (there may be more than one) is returned for use:

private String findMatch(String myString) {

    String match = "";

    // Pattern to find code
    String pattern = "[0-9]{8}";  // Sequence of 8 digits
    Pattern regEx = Pattern.compile(pattern);

    // Find instance of pattern matches
    Matcher m = regEx.matcher(myString);
    if (m.find()) {
        match = m.group(0);
    }
    return match;
}

Hopefully this simple guide is enough of an introduction to the basics to get you going. There are many good resources on the web to help you build patterns and also libraries of commonly used patterns, regexlib.com for example. Now you'll be knocking out expressions in no time!

0 comments:

Post a Comment