Skip to content
C

Regular Expressions

A regular expression (regex) is a pattern used to match, search, or validate specific formats within text — like checking if a string looks like a valid email address or a valid phone number.


1. What are Regular Expressions?

A regular expression (regex) is a pattern used to match, search, or validate specific formats within text — like checking if a string looks like a valid email address or a valid phone number.

2. Why is it used?

Regular expressions let you validate or search text based on a pattern rule, instead of writing long, manual character-by-character checks yourself.

3. Real-Life Example

Think of a security checkpoint with a specific rule: "Only ID cards matching this exact format (2 letters followed by 6 digits) are valid." A regular expression defines and checks this kind of pattern rule against text automatically.

4. Syntax

java
String text = "example123"; boolean matches = text.matches("regexPattern");

5. Example Program

java
public class RegexDemo { public static void main(String[] args) { String email = "student@example.com"; boolean isValid = email.matches("^[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}$"); System.out.println("Valid email: " + isValid); } }

Output:

Valid email: true

6. Key Points to Remember

  • String.matches() checks if the entire string fits the given pattern.
  • The java.util.regex package (with Pattern and Matcher classes) offers more advanced regex operations, like finding partial matches.
  • Regex patterns can look complex at first, but common patterns (email, phone number, pin code) are widely available for reference and reuse.