x
Loading
 Loading
Hello, Guest | Login | Register

Java Regular Expressions

Java’s string processing capabilities are far better than those found in C, C++, or Visual Basic, but aren’t quite as powerful as, say, Perl’s. While the Java String class provides convenient methods such as indexOf(), lastIndexOf(), and startsWith(), you still have to write quite a bit of Java code to do something like break a colon-delimited record into a set of fields. Until now.

Java’s string processing capabilities are far better than those found in C, C++, or Visual Basic, but aren’t quite as powerful as, say, Perl’s. While the Java String class provides convenient methods such as indexOf(), lastIndexOf(), and startsWith(), you still have to write quite a bit of Java code to do something like break a colon-delimited record into a set of fields. Until now.

Java 2 Standard Edition (J2SE) 1.4 adds the power of Perl-like regular expressions to Java. Indeed, even the syntax of regular expressions in the new Java package is nearly identical to Perl’s. This month, we continue our survey of new J2SE 1.4 features and focus on the classes and methods in java.util.regex.

Perls of Java

To get the most out of this article, you should already be familiar with Perl’s regular expression syntax. If you’re not, see this month’s feature on regular expressions, “Hitting the Motherlode,” (pg. 32), before you continue. Having said that, let’s jump right in.

As mentioned above, Java’s regular expressions are nearly identical to the notation used in Perl. You can use all the Perl metacharacters (e.g., ^ ( ) [] $ ? *) and all the Perl character class abbreviations (. for any character except newline, \d for digits, \D for non-digits, etc.). There’s just one small change: since the \ character has a special purpose in Java strings (it’s used to specify a character by its ASCII value in either octal or hexadecimal), you have…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace