Cheatsheet for Java Regex

Java regex is the Java implementation of regular expressions, which are a way to match patterns in text. Regular expressions are used to search, edit, and manipulate text and can be used for a variety of tasks such as validating input, parsing data, and finding and replacing strings.

Patterns

  • . matches any single character (except a newline)
  • [abc] matches any of the characters a, b, or c
  • [^abc] matches any character except a, b, or c
  • \d matches a digit (same as [0-9])
  • \D matches a non-digit (same as [^0-9])
  • \s matches a whitespace character (includes tabs and line breaks)
  • \S matches a non-whitespace character
  • \w matches a word character (same as [a-zA-Z_0-9])
  • \W matches a non-word character
  • {n} matches exactly n occurrences of the preceding character or pattern
  • {n,} matches at least n occurrences of the preceding character or pattern
  • {n,m} matches at least n and at most m occurrences of the preceding character or pattern
  • * matches zero or more occurrences of the preceding character or pattern
  • + matches one or more occurrences of the preceding character or pattern
  • ? matches zero or one occurrences of the preceding character or pattern
  • ^ matches the beginning of a line
  • $ matches the end of a line
  • (pattern) captures the matched pattern for later use (using Matcher.group())
  • (?:pattern) non-capturing group
  • (?=pattern) positive lookahead assertion
  • (?!pattern) negative lookahead assertion

Examples

  • \d{3}-\d{3}-\d{4} matches a phone number in the format 123-456-7890
  • [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4} matches an email address
  • https?://.+ matches a URL starting with http or https

Usage

To use regex in Java, you will need to import the java.util.regex package and use the Pattern and Matcher classes.

Here is an example of using regex to find all occurrences of a pattern in a string:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    String input = "The quick brown fox jumps over the lazy dog.";
    String pattern = "\\b[a-z]{5}\\b"; // matches 5-letter words

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(input);

    while (m.find()) {
      System.out.println(m.group());
    }
  }
}

This will print the following output:

brown
jumps
over
lazy

You can also use the replaceAll or replaceFirst methods of the Matcher class to replace matched patterns in a string.

For more information, you can refer to the Java documentation for the Pattern