Skip to Main Content
Regular Expression Pocket Reference, 2nd Edition
book

Regular Expression Pocket Reference, 2nd Edition

by Tony Stubblebine
July 2007
Intermediate to advanced content levelIntermediate to advanced
128 pages
2h 39m
English
O'Reilly Media, Inc.
Content preview from Regular Expression Pocket Reference, 2nd Edition

Examples

Example 1-5. Simple match

import java.util.regex.*;

// Find Spider-Man, Spiderman, SPIDER-MAN, etc.
public class StringRegexTest {
  public static void main(String[] args) throws Exception {
    String dailyBugle = "Spider-Man Menaces City!";

      //regex must match entire string
    String regex = "(?i).*spider[- ]?man.*";

    if (dailyBugle.matches(regex)) {
      System.out.println("Matched: " + dailyBugle);
    }
  }
 }

Example 1-6. Match and capture group

// Match dates formatted like MM/DD/YYYY, MM-DD-YY,...
import java.util.regex.*;

public class MatchTest {
  public static void main(String[] args) throws Exception {
    String date = "12/30/1969";
    Pattern p =
       Pattern.compile("^(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\
\d)?)$");
    Matcher m = p.matcher(date);

    if (m.find( )) {
      String month = m.group(1);
      String day   = m.group(2);
      String year  = m.group(3);
      System.out.printf("Found %s-%s-%s\n", year, month, day);
    }
  }
 }

Example 1-7. Simple substitution

// Example -. Simple substitution
// Convert <br> to <br /> for XHTML compliance
import java.util.regex.*;

  public class SimpleSubstitutionTest
 {  public static void main(String[] args) {
    String text = "Hello world. <br>";
    Pattern p = Pattern.compile("<br>", Pattern.CASE_
INSENSITIVE);
    Matcher m = p.matcher(text);

    String result = m.replaceAll("<br />");
    System.out.println(result);
  }
 }

Example 1-8. Harder substitution

// urlify - turn URLs into HTML links import java.util.regex.*; public class Urlify { public static void main (String[ ] args) throws Exception { String text ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Advanced for the World Wide Web: Visual QuickPro Guide

PHP Advanced for the World Wide Web: Visual QuickPro Guide

Larry Ullman
PHP 5 Power Programming

PHP 5 Power Programming

Andi Gutmans, Stig Sæther Bakken, Derick Rethans

Publisher Resources

ISBN: 9780596514273Errata Page