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 ...

Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.