Regex with Strings

Regular expressions (Regex) are powerful tools for pattern matching and text manipulation. In Java, Regex is often used to search, match, and replace substrings within a string based on specific patterns. It’s a key skill for developers dealing with text processing, validation, or data extraction.

What is Regex?

A Regular Expression is a sequence of characters that form a search pattern. It allows you to describe text patterns that can match one or more strings. In Java, you can use the Pattern and Matcher classes to work with regular expressions.

Common Uses of Regex in Java

  • Searching for patterns: Check if a string matches a specific format (e.g., email, phone number).
  • Replacing parts of a string: Modify strings based on matching patterns.
  • Validating input: Ensure user input matches a certain format, like validating a password.
  • Extracting data: Pull specific information out of text, such as extracting dates from a string.

Basics of Regex Syntax

Regex syntax can seem a little daunting at first, but once you understand the basics, you can create powerful patterns. Here are a few important components:

  • Metacharacters: These are special characters that have specific meanings in regex:
    • . (dot): Matches any single character (except newline).
    • ^: Anchors the match at the beginning of the string.
    • $: Anchors the match at the end of the string.
    • \d: Matches any digit (0-9).
    • \w: Matches any word character (letters, digits, underscores).
    • \s: Matches any whitespace character (spaces, tabs, etc.).

Using Pattern and Matcher

In Java, the Pattern class is used to define a compiled regex expression, and the Matcher class is used to search through a string. Let’s look at how you can use these classes to perform basic regex tasks:

Example: Checking if a String Matches a Pattern

In this example, the regex \w+ matches one or more word characters. The matcher.matches() method checks if the entire string matches the pattern.

Example: Finding All Matches in a String

You can also use Matcher to find all occurrences of a pattern within a string.

This code will find and print all phone numbers that match the pattern XXX-XXX-XXXX in the provided text.

Example: Replacing Text with Regex

You can use regex to replace parts of a string that match a specific pattern.

In this case, replaceAll replaces every occurrence of “Java” with “JavaScript” in the string.