Using Regular Expressions in Java for Data Validation Evelyn Brannock Jan 30, 2009.
-
Upload
marlene-hood -
Category
Documents
-
view
216 -
download
1
Transcript of Using Regular Expressions in Java for Data Validation Evelyn Brannock Jan 30, 2009.
Using Regular Expressions in Java
for Data Validation
Evelyn Brannock
Jan 30, 2009
Definition
They are usually used to give a concise description of a set, without having to list all elements
A regular expression is an expression that describes a set of strings
Origin In the 1950s, mathematician Stephen Cole
Kleene devised a way to describe and classify formal languages using his mathematical notation called regular sets
Using Regular Expressions for Data Validation
Regular Expressions
Construct Matchesx The character x
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a-zA-Z] a through z or A through Z, inclusive (range)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
*from the Sun Java API
Regular Expressions
Construct MatchesX? X, once or not at all
X* X, zero or more times
X+ X, one or more times
X{n} X, exactly n times
X{n,} X, at least n times
X{n,m} X, at least n but not more than m times
XY X followed by Y
X|Y Either X or Y
*from the Sun Java API
Examples
Searching for a wordMatching an email addressVerifying the format of a telephone numberCredit card pre-validation IP address determinationZip code format validation
The regular expression built is determined by the definition of valid values for the field
Building a Regular Expression**Matching a Word**
Words that start with t, with at least one additional letter, all lowercase
t[a-z]+What if the word can start with a
lowercase or uppercase t? [t|T][a-z]+What if no additional letters must follow
(but they may)?
Building a Regular Expression **Validating and IP Address**
What does an IP address look like?Are three digits required? Is 999.999.999.999 a valid IP?25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?
Steps
Whitespace will often need to be strippedDetermine the valid values of the stringCreate the regular expressionCompile the regular expression into a
patternPlace the string you wish to validate into
the Matcher classDoes the string match the pattern?
Java Invocation Sequence
Two Java classes required:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
Code:
Pattern p = Pattern.compile("a*b"); Matcher m = p.matcher("aaaaab"); boolean b = m.matches();
U.S. Zip Code
What is a valid expression for a zip code?Let’s build the regular expression together
using GGCCustomerZipCode.java
Further Reading
Teach Yourself Regular Expressions in 10 Minutes by Ben Forta
Mastering Regular Expressions by Jeffrey Friedl Java Regular Expressions by Mehran Habibi Regular Expression Pocket Reference by Tony
Stubblebine Regular Expression Recipes by Nathan Good
Questions