Regex
Regex
Note:
- Regex is used with the Pattern and Matcher classes in java.util.regex
- Commonly used for string searching, validation, parsing, etc.
--------------------------------------------------
Basic Syntax
. Matches any character except newline
\d Digit (0-9)
\D Non-digit
\w Word character (a-z, A-Z, 0-9, _)
\W Non-word character
\s Whitespace (space, tab, etc.)
\S Non-whitespace
--------------------------------------------------
Anchors
^ Start of string
$ End of string
\b Word boundary
\B Not a word boundary
--------------------------------------------------
Quantifiers
* 0 or more times
+ 1 or more times
? 0 or 1 time
{n} Exactly n times
{n,} n or more times
{n,m} Between n and m times
--------------------------------------------------
Character Classes
[abc] Matches 'a', 'b', or 'c'
[^abc] Not 'a', 'b', or 'c'
[a-z] Any lowercase letter
[A-Z] Any uppercase letter
[0-9] Any digit
--------------------------------------------------
--------------------------------------------------
Escaping
\\ Escape character in Java (double backslash)
\\. Literal dot
\\d Use two backslashes in Java strings
Example:
String regex = "\\d{3}-\\d{2}-\\d{4}"; // SSN format
--------------------------------------------------
Common Examples
// Validate email
str.matches("^[\\w.-]+@[\\w.-]+\\.\\w+$");
--------------------------------------------------
import java.util.regex.*;
if (matcher.matches()) {
System.out.println("Match found!");
}
--------------------------------------------------
--------------------------------------------------
--------------------------------------------------