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