The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Bonus
Lesson: Regular Expressions

## Introduction

> ### What are regular expressions?

> Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used as a tool to search, edit or manipulate text or data. You must learn a specific syntax to create regular expressions--one that goes beyond the normal syntax of the JavaTM programming language. Regular expressions range from being simple to quite complex, but once you understand the basics of how they're constructed, you'll be able to understand any regular expression.

> This tutorial will teach you the regular expression syntax supported by the `java.util.regex` API, and will present plenty of working examples to illustrate how the various objects interact. In the world of regular expressions, there are many different flavors to choose from, such as grep, Perl, Tcl, Python, PHP, and awk. The regular expressions in the `java.util.regex` API are most similar to Perl.

> ### How are regular expressions represented in this package?

> The `java.util.regex` package consists of three classes: `Pattern`, `Matcher`, and `PatternSyntaxException`.

> - A `Pattern` object is a compiled representation of a regular expression. The `Pattern` class provides no public constructors. To create a pattern, you must call one of its public static `compile` methods, both of which will return a `Pattern` object. You should understand regular expressions fairly well to use these methods since they accept a regular expression (a string) as their first argument. The first few lessons of this tutorial will teach you the required syntax.

> - A `Matcher` object is the engine that interprets the pattern and performs match operations against an input string. Like the `Pattern` class, `Matcher` defines no public constructors. You obtain a `Matcher` object by calling the public `matcher` method on a `Pattern` object.

> - A `PatternSyntaxException` object is an unchecked exception that indicates a syntax error in a regular expression pattern.
> In the last few sections in this lesson, we'll explore each class in detail with a separate section devoted to each class. But first, let's learn the details of how regular expressions are created. The next section introduces a simple test harness that we'll use repeatedly to explore how regular expressions are constructed.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.