Java Reference
In-Depth Information
Chapter 14
Regular Expressions
In this chapter, you will learn
How to create regular expressions
String class to perform regular expression-based
How to use convenience methods in the
find-and-replace
Pattern class to compile regular expressions
How to use the
Matcher class to match a regular expression against an input string
How to use the
How to use groups in regular expressions
Matcher class
How to perform advanced find-and-replace using the
What Is a Regular Expression?
A regular expression is a way to describe a pattern in a sequence of characters. The pattern may be used to validate
the sequence of characters, to search through the sequence of characters, to replace the sequence of characters
matching the pattern with other sequence of characters, etc.
Let's start with an example. Suppose you have a string, which may be an e-mail address. How would you make
sure that the string is in a valid e-mail address format? At this point, you are not interested in the existence of the
e-mail address. You just want to validate its format.
You would like to validate the string against some rules. For example, it must contain an @ sign, which is preceded
by at least one character and followed by a domain name. Optionally, you may specify that the text preceding the
@ sign must contain only letters, digits, underscores, and hyphens. The domain name must contain a dot. You may
want to add some more validations. If you just want to check for a @ character in a string, you can do it by calling
email.indexOf('@') , where email is the reference of the string holding the e-mail address. If you want to make sure that
there is only one @ character in the e-mail string, you need add more logic to the code. In such cases, you may end up
with 20 to 50 , or even more, lines of code depending on the number of validations you want to perform. This is where
regular expressions come in handy. It will make your e-mail address validation easy. You can accomplish it in just one
line of code. Doesn't that sound too good to be true? Just a little while ago, you were told that you might end up with
50 lines of code. Now you are told that you could accomplish the same in just one line of code. This is true. It can be
done in one line of code. Before I go into the details of how to do this, let's list the steps needed to accomplish this task.
 
Search WWH ::




Custom Search