gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Promote Your Website
Computer Hardware
Baby Photo Contest
Logo Design
Shop
Promotional Gifts
Imprinted Promotions
Remote Online Backup
Promos and Premiums
GPS
Rackmount LCD Monitor
Prepaid Phone Card
KVM over IP
Shop Online

 


Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Class of the Month: JDK 1.4 Supports Regular Expressions
By Piroz Mohseni

Regular expressions have been around for a long time. They come in very handy for text processing tasks. Some attribute the success of Perl to its superb ability of handling regular expressions. While there have been third-party classes that support regular expressions, with JDK 1.4, Java provides native support via the java.util.regex package.

Piroz Mohseni

Usage of regular expressions boils down to two components:

  1. Defining the regular expression. This is a pattern that describes what is to be matched.
  2. Applying the regular expression on a sequence of characters. Determining whether a match was found or not, successive finds, and replacements are some of the common operations involving regular expressions.

The Pattern class focuses on the first component. You use this class to define a regular expression. By representing the regular expression as an object, you can reuse the expression in your code. This is particularly useful in cases where you need to apply the same expression to multiple strings (e.g., line-by-line processing of a text file). The following line creates a pattern based on the regular expression "[0-9]" which matches any digits from 0 to 9. This pattern can also be represented as "/d".

Pattern p = Pattern.compile("[0-9]");

The documentation for the Pattern class provides a useful summary of regular expression constructs. It also provides a comparison to Perl 5 regular expressions. The Pattern class includes several fields that allow you to control its behavior. They include CANON_EQ, CASE_SENSITIVE, DOTALL, MULTILINE, and UNICODE_CASE. You can pass these flags to the compile() method to alter its behavior. For example, CASE_SENSITIVE enables case-sensitive matching. The pattern() method returns a String representing the regular expression that was compiled. The matcher() method takes a CharSequence as input and creates a "matcher" object that will be used to apply the regular expression. The matches() method returns a boolean after applying the regular expression and the split() method returns an array of Strings after attempting to split its input around matches found based on the pattern.

Once you have the pattern defined, you will use the Matcher class to apply that pattern to a character sequence (usually a String). The following two lines demonstrate this:

Matcher m = p.matcher("abcd55efg");
boolean matchFound = m.matches();

Listing 1 is a simple class that searches for a pattern consisting of characters followed by two digits, followed by more characters. The pattern is applied to the string "abcd55efg" and the result is printed. In this case, a match should be found. To experiment with various regular expressions, you can make the arguments to the compile() and matcher() methods correspond to the command-line parameters.

Listing 1.

import java.util.regex.*;
class regexSample {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("[a-z]*[0-9][0-9][a-z]*");
      Matcher m = p.matcher("abcd55efg");
      boolean matchFound = m.matches();
      if (matchFound)
        System.out.println("Match was found.");
      else
        System.out.println("No match.");
   }
}

Aside from a "match" operation, the Matcher class provides a number of other methods. Once a match is found, the start() and end() methods return the starting and ending index of the characters in the match. These values are useful if successive matching is needed using the find() method. Unlike matches(), the find() method will return true when a portion of the input source matches the regular expression pattern. Listing 2 shows the same class but with the find() method. The regular expression has been changed to "[0-9][0-9]" , which is two successive digits.

Listing 2.

class regexSample2 {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("[0-9][0-9]");
      Matcher m = p.matcher("abcd55efg");
      boolean matchFound = m.find();
      if (matchFound)
        System.out.println("Match was found.");
      else
        System.out.println("No match.");
   }
}

We will get a match because the pattern of two successive digits is within the input source (i.e., 55).

The lookingAt() method tries to find the pattern starting from the beginning of the input source. If you change the input source in Listing 2 to "55abcdefg", then using the lookingAt() method, you will get a match because the beginning of the input source is a sequence of two successive digits. There are also methods like appendReplacement() and replaceAll(), which allow you to make changes to the input sequence based on the regular expression.

Regular expressions are a useful programming tool. The fact that Java now natively supports them simplifies many programming tasks that used to require cumbersome code dealing with character arrays and StringTokenizer.

About the Author

Piroz Mohseni is a principle with Bita Technologies, focusing on business improvement through the effective use of technology. His areas of interest include enterprise Java, XML, and e-commerce applications.


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Java Archives

Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Whitepaper: XML Processing in Applications--Take the Next Step
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES