Web Analytics

Regular Expressions (Regex)

Intermediate ~20 min read

Regular Expressions are an API for defining String patterns that can be used for searching, manipulating, and editing text.

The API

The core classes are in java.util.regex:

  • Pattern: A compiled representation of a regular expression.
  • Matcher: An engine that interprets the pattern and performs match operations against an input string.

Basic Example

import java.util.regex.*;

String text = "This is a java tutorial.";
String patternString = ".*java.*";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

boolean matches = matcher.matches(); // true

Common Syntax

Expression Meaning
. Any character
^ Start of string
$ End of string
\d Any digit (0-9)
\w Word character (a-z, A-Z, 0-9, _)

Full Example

Output
Click Run to execute your code

Summary

  • Regex is a powerful tool for text processing.
  • Java uses java.util.regex package.
  • Remember that backslashes \ in strings need to be escaped (e.g., "\\d").