Java Regular Expressions (Regex)

Java Regular Expressions (Regex)

Regular Expressions (Regex) are patterns used to match character combinations in strings.
In Java, regex is supported via the java.util.regex package.

  • Main classes: Pattern and Matcher

  • Used for validation, search, and text processing


1. Key Classes

ClassDescription
PatternCompiles a regex pattern
MatcherPerforms match operations on a string
PatternSyntaxExceptionException for invalid regex patterns

 2. Basic Syntax

SymbolMeaning
.Any character
\dDigit (0-9)
\DNon-digit
\wWord character (a-z, A-Z, 0-9, _)
\WNon-word character
\sWhitespace
\SNon-whitespace
^Start of string
$End of string
*Zero or more occurrences
+One or more occurrences
?Zero or one occurrence
{n}Exactly n occurrences
{n,}n or more occurrences
{n,m}Between n and m occurrences
[]Character class
``

3. Example: Simple Match


 

  • matches() checks entire string against pattern


4. Example: Find All Matches


 

  • find() searches all occurrences in the string

  • group() returns the matched substring


 5. Example: Replace Using Regex


 

  • replaceAll() replaces all matches with specified string


6. Example: Validate Email


 

  • matches() validates the entire string against pattern


7. Common Regex Patterns

PatternDescription
\\d{10}10-digit number
\\w+One or more word characters
[a-zA-Z]+Alphabetic characters only
\\s+One or more whitespace characters
^[A-Z]Starts with uppercase letter
\\S+@\\S+\\.\\S+Simple email validation

 Best Practices

  1. Use Pattern.compile() when using the same regex multiple times.

  2. Escape special characters with \\ in Java strings.

  3. Use matches() for full string validation, find() for searching within text.

  4. Consider regex readability for complex patterns.


Summary

  • Java supports regex using Pattern and Matcher

  • Use regex for validation, searching, replacing, and splitting

  • Supports quantifiers, character classes, anchors, and groups

You may also like...