Java: Regular Expressions
Regular expressions are the most common programming technique to search for patterns in strings, extracting, and replacing substrings. They are an essential part of many languages, editors, and utilities, for example, Perl, JavaScript, awk, sed, vi, ....
They are powerful and useful. Simple regexes are simple, but large regexes are extremely difficult to debug. They are often not the right solution for complex parsing problems. Two quotes illustrate some feelings about them. Despite the name, as someone said, Regular expressions are neither regular nor expressions. And Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. Regular expressions form a quirky, error-prone, terse, but useful, programming language for pattern matching.
Java, as of version 1.4, has extensive support for regular expressions in two areas.
- additional String methods. See String Regex Methods.
- Additional classes,
java.util.Pattern
andjava.util.Matcher
, allow use of precompiled regular expressions as well as providing many additional functions. See Pattern and Matcher.
Regular expressions provide more general mechanisms for parsing input
strings than, eg, StringTokenizer
.
Programming language. Regular expressions (often refereed to as regex) are essentially a programming language of their own.
Other Resources
- Regular Expression Tutorial (http://www.regular-expressions.info/tutorial.html) covers a lot of introductory regular expression material.
- Mastering Regular Expressions by Jeffrey Friedl is an excellent book covering regular expressions from introduction to advanced usage. Covers all major regular expression implementations, not just Java.
- Regular Expressions and the Java Programming Language (http://java.sun.com/developer/technicalArticles/releases/1.4regex) is a Sun article summarizing Java's regular expressions. This is useful if you are already familiar with Java and the idea of regular expressions.
- JRegexpTester - jregexptester.sourceforge.net/ - Another free Java program to test regexes.
- RegExLib.com - www.regxlib.com/ - Has blog discussing regeexps, and a large (> 900) library of regexps of all flavors, not just Java.
- Regular Expressions in J2SE - http://www.onjava.com/pub/a/onjava/2003/11/26/regex.html - Introduction to regular expressions.
- Summary of Regular Expressions in Java and other languages - http://mindprod.com/jgloss/regex.html
- Regular Expression Test Page - www.fileformat.info/tool/regex.htm