Java RegEx Tester
Search...
⌘K
Java RegEx Tester
Search...
⌘K


Java RegEx Tester
Test and debug Java regular expressions instantly using the Qodex Java RegEx Tester, powered by the java.util.regex engine. Get real-time feedback with match highlights, capture groups, and syntax error detection—making it ideal for tasks like email validation, password matching, and pattern-based string parsing.
Whether you’re building login forms, input validators, or custom parsers, this tool streamlines your Java regex workflow. For comprehensive testing, pair it with the Email Generator, UUID Generator, or Password Generator to generate realistic test inputs.
Fine-tune specific fields with our Email Regex Java Validator or Phone Number Regex Java Validator to ensure your patterns are both precise and production-ready.
[A-Z]
: uppercase letters[a-z]
: lowercase letters[0-9]
: digits\.
: a literal dot+
: one or more of the preceding*
: zero or more of the preceding?
: optional (zero or one)^
: start of string$
: end of string
Test your APIs today!
Write in plain English — Qodex turns it into secure, ready-to-run tests.
Regular Expression - Documentation
Java Regex Tester
The Java Regex Tester by Qodex helps developers write, test, and debug regular expressions in real time using Java’s java.util.regex package. It supports instant pattern testing for emails, passwords, phone numbers, dates, credit cards, and more.
You can view live match results, capture groups, and syntax feedback instantly—making it easy to refine your regex before using it in Java code.
How to Use:
Enter your regular expression.
Provide a test string.
Instantly see highlighted matches and capture groups.
Need test inputs? Try our:
Java Regex Syntax Essentials
Meta characters
.
: Matches any single character except newline characters (``).
Commonly used to represent any wildcard character.^
: Anchors the match at the beginning of a line or string.
Example:^abc
matchesabc
only if it’s at the start.$
: Anchors the match at the end of a line or string.
Example:xyz$
matchesxyz
only at the end.``: Acts as a logical OR operator.
Example:catdog
matches either cat or dog. Useful for alternatives.
Character Classes
[abc]
: Matches any one character: eithera
,b
, orc
.[^abc]
: Matches any character excepta
,b
, orc
. The caret^
negates the set.[a-zA-Z]
: Specifies a range, matches any uppercase or lowercase letter from a to z.
Predefined Character Classes
\d
: Matches any digit character; equivalent to[0-9]
.\D
: Matches any non-digit character; equivalent to[^0-9]
.\s
: Matches any whitespace character (space, tab, newline).\S
: Matches any non-whitespace character.\w
: Matches any word character (letters, digits, or underscore); equivalent to[a-zA-Z0-9_]
.\W
: Matches any character that is not a word character.
Quantifiers
*
: Matches the preceding element zero or more times.
Example:lo*l
matchesll
,lol
,lool
, etc.+
: Matches one or more occurrences.
Example:lo+l
matcheslol
,lool
, but notll
.?
: Matches zero or one occurrence. Also makes quantifiers lazy when placed after them
Example:*?
{n}
: Matches exactly n occurrences.
Example:a{3}
matchesaaa
.{n,}
: Matches n or more occurrences.
Example:a{2,}
matchesaa
,aaa
,aaaa
, etc.{n,m}
: Matches between n and m occurrences.
Example:a{2,4}
matchesaa
,aaa
, oraaaa
.
Groups and Capturing
(abc)
: Captures and groups the match forabc
. This can be reused with backreferences.(?:abc)
: Groupsabc
without capturing it. Useful for applying quantifiers or alternation without creating references.(?i)abc
: Enables case-insensitive matching for the group. Matchesabc
,ABC
,AbC
, etc.\b
: A word boundary.\B
: A non-word boundary.\1
,\2
, etc.: Backreferences to captured groups.
Example:(\w+)\s\1
matches repeated words likehello hello
.
Matching a Backspace Character
[\b]
: Matches a backspace character (ASCII 0x08).
This is rarely needed in typical text processing, but can be useful when working with legacy data or control characters. Note: in most regular expression dialects, \b
by itself refers to a word boundary. When placed inside square brackets ([...]
), it specifically targets the backspace control character.
Logical Assertions (Lookaheads & Lookbehinds)
(?=...)
: Positive lookahead. Ensures what follows the current position matches the pattern inside.
Example:\d(?=px)
matches a digit only if it’s followed bypx
.(?!...)
: Negative lookahead. Ensures the following characters do not match the pattern.
Example:foo(?!bar)
matchesfoo
only if it’s not followed bybar
.(?<=...)
: Positive lookbehind. Ensures that what precedes the current position matches the pattern.
Example:(?<=@)\w+
matches the username after an@
.(?<!...)
: Negative lookbehind. Ensures that what precedes is not a match.
Example:(?<!(https:))//
matches//
not preceded byhttps:
.
Greedy vs Lazy Quantifiers
*?
: Matches as few as possible, zero or more times.+?
: Matches as few as possible, one or more times.??
: Matches as few as possible, zero or one time.{n}?
: Matches exactly n times, but tries to do it minimally.{n,}?
: Matches at least n times, but lazily.{n,m}?
: Matches between n and m times, choosing the smallest match possible.
Lazy quantifiers are useful when you’re trying to avoid consuming too much text—especially helpful for nested tags or repeated delimiters.
Unicode Support
\p{L}
: Matches any kind of letter from any language.\p{N}
: Matches any kind of numeric character.\p{IsGreek}
: Matches any character in the Greek Unicode block.\P{...}
: The inverse of\p{...}
. For example,\P{L}
matches any non-letter character.
Unicode properties allow your regex to work globally—great for international applications.
Common Patterns for Number Validation
Regular expressions are invaluable for validating and parsing numbers of various formats. Here are some frequently used patterns for number validation in Java regex:
Positive integers of undefined length
^\d+$
Matches any positive integer (e.g., 123
, 987654
).
Positive integers of maximum length (10 in this example)
^\d{1,10}$
Ensures the integer has up to 10 digits.
Positive integers of fixed length (5 in this example)
^\d{5}$
Matches exactly 5 digits.
Negative integers of undefined length
^-\d+$
Matches any negative integer (e.g., -123
, -45678
).
Negative integers of maximum length (10 in this example)
^-\d{1,10}$
Negative integer up to 10 digits.
Negative integers of fixed length (5 in this example)
^-\d{5}$
Exactly 5 digits, negative.
Integers of undefined length (positive or negative)
^-?\d+$
Matches either positive or negative integers.
Integers of maximum length (10 in this example)
^-?\d{1,10}$
Positive or negative integer up to 10 digits.
Integers of fixed length (5 in this example)
^-?\d{5}$
Exactly 5 digits, with optional negative sign.
Numbers with or without decimals
^-?\d*\.{0,1}\d+$
Matches numbers such as 1234
, -56.78
, .25
, or 0.123
.
Numbers with 2 decimals
^-?\d*\.\d{2}$
Ensures exactly two decimal places (e.g., 42.00
, -3.14
).
Currency numbers with thousands separators, optional decimals, and optional symbol
^$?\-?([1-9]{1}[0-9]{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))$^\-?$?([1-9]{1}\d{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))$^\($?([1-9]{1}\d{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))\)$
Covers a wide range of currency inputs including optional dollar sign, commas for thousands, and up to two decimals.
Percentage values from 0 to 100, with up to 2 decimals and an optional % sign
^-?[0-9]{0,2}(\.[0-9]{1,2})?%?$^-?(100)(\.[0]{1,2})?%?$
Matches 0
, 0.00
, 100
, 99.99%
, and similar forms.
These patterns, combined with the core syntax above, equip you to validate and parse most numeric formats encountered in everyday Java development—whether it’s user input, API payloads, or data files.
Common Java Regex Examples
Email Validation
Use with Email Regex Java Validator
Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
Strong Password Check
Test using Password Regex Java Validator.
"(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}"
Phone Number Formats
Covers (123) 456-7890, 1234567890, 123-456-7890
Pattern.compile("^(\\d{10}|\\(\\d{3}\\)[\\s.-]?\\d{3}[\\s.-]\\d{4}|\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4})$")
Validating US and Canadian Phone Numbers
Looking to verify North American phone numbers with Java RegEx? There are several formats users tend to enter, such as:
999-999-9999
(999) 999-9999
9999999999
A flexible pattern can help catch these common variations. Here’s how you can implement it:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String[] phones = {
"123-456-7890",
"(123) 456-7890",
"1234567890",
"123.456.7890",
"123 456 7890"
};
Pattern phonePattern = Pattern.compile("^(\\d{10}(\\(?\\d{3}\\)?[ .-]?\\d{3}[ .-]\\d{4}))$");
for (String phone : phones) {
Matcher matcher = phonePattern.matcher(phone);
System.out.println(phone + " Valid: " + matcher.matches());
}
}
}
This approach accommodates the typical separators—spaces, dashes, or dots—and even an optional area code in parentheses. Adjust as needed if your project requires stricter formatting rules!
Credit Card Pattern Matching
Use Credit Card Regex Java Validator + Luhn check for full validation.
Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$") // VISA
Date Formats (ISO / US)
Regex checks format only—use Java date libraries for real validation.
For more thorough validation—including leap years, months with 30 vs. 31 days, and so on—consider using Java’s built-in or libraries like Apache Commons Validator. Regex is your first line of defense, but not your only one!
"\\d{4}-\\d{2}-\\d{2}" // ISO "\\d{2}/\\d{2}/\\d{4}" // US MM/DD/YYYY
Extract Filename from Windows Path
Pattern.compile("[^\\\\]+$");
IPv4 Address Validation
Want to ensure a string is a valid IPv4 address? The regular expression below checks that each number (octet) falls between 0 and 255, blocking out values like 999.999.999.999. Here’s how you can validate an IP address in Java:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String ip = "192.168.0.1";
String regex = "^(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ip);
System.out.println("IP Valid: " + matcher.matches());
}
}
Tips:
To check for an IPv4 address inside a larger text, you can remove the
^
and$
anchors and use word boundaries like\\b
.Each octet is checked to be between 0 and 255, preventing invalid versions such as 300.400.500.600.
This approach is handy for input validation in networking tools, login forms, or whenever you need to be sure you’re dealing with a proper IPv4 address.
Validating 24-hour Time Format (HH:MM)
Need to check if a string is a properly formatted time, like "14:45" or "09:02"? You can handle this with a regular expression that matches 24-hour time in the HH:MM format.
Here's a quick Java snippet for validating time strings:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String time = "23:59";
Pattern pattern = Pattern.compile("^([01]\\d2[0-3]):[0-5]\\d$");
Matcher matcher = pattern.matcher(time);
System.out.println("Time Valid: " + matcher.matches());
}
}
How this pattern works:
([01]\\d2[0-3])
ensures hours are between 00 and 23.:[0-5]\\d
ensures minutes are between 00 and 59.
Give it a spin. Try plugging in values like "00:00", "12:30", or "24:00" (which should fail) to see if your validation logic holds up.
Validate Hex Colors
Ever wanted to make sure that hex color code you grabbed from Photoshop or Figma is actually legit? A simple regex can help you verify both the short (3-digit) and long (6-digit) hex codes, with or without that trusty leading .
java import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String[] colors = { "#1a2B3c", "123", "#ABCDEF", "#zzz", "FFF0A" }; Pattern hexPattern = Pattern.compile("^#?([a-fA-F0-9]{6}[a-fA-F0-9]{3})$"); for (String color : colors) { Matcher matcher = hexPattern.matcher(color); System.out.println(color + " is valid hex: " + matcher.matches()); } } }
This regex checks if a string starts with an optional , followed by either exactly 3 or 6 hexadecimal digits. It’s case-insensitive so you don’t have to worry about uppercase vs. Lowercase.
SIN / SSN / ZIP Code Patterns
Check formatting only. Use:
^\d{3}-\d{2}-\d{4}$ for SSN
^\d{5}(-\d{4})?$ for ZIP +4
How do I validate a US ZIP code or ZIP+4 format using a regular expression?
Need to make sure your ZIP code input measures up to USPS standards? US postal codes come in two flavors: the classic five-digit version and the fancier ZIP+4, which tacks on a hyphen and four more digits.
Here’s how you can check for both formats using Java regular expressions:
Just the basics:
Five digits, and only five:
^\d{5}$
ZIP+4 (going the extra mile):
Five digits, optionally followed by a hyphen and four more digits:
^\d{5}(-\d{4})?$
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String zip = "90210-1234";
Pattern zipPattern = Pattern.compile("^\\d{5}(-\\d{4})?$");
Matcher matcher = zipPattern.matcher(zip);
System.out.println("ZIP Valid: " + matcher.matches());
}
}
Plug in your favorite ZIP or ZIP+4 and see if it passes muster!
Canadian Postal Code Validation
Want to check if a string is a valid Canadian postal code? Their format follows the pattern A1B 2C3
—alternating letters and digits, with an optional space in the middle (but don't expect any Z’s, D’s, or U’s—Canada Post skips those).
Here's a Java snippet to get you started:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String postalCode = "K1A 0B1";
Pattern pattern = Pattern.compile("^[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(postalCode);
System.out.println("Canadian Postal Code Valid: " + matcher.matches());
}
}
This regular expression ensures the code matches the required format and only accepts valid starting letters. Give it a try with your favorite Toronto or Vancouver postal codes!
How do I validate a Canadian Social Insurance Number (SIN) format using a regular expression?
If you've ever needed to check if a string fits the Canadian SIN pattern, regular expressions have your back. This regex tolerates common SIN variations like 123456789
, 123-456-789
, or 123 456 789
(just make sure the separators are consistent throughout):
String sin = "123-456-789";
Pattern sinPattern = Pattern.compile("^\\d{3}([\\s-])?\\d{3}\\1\\d{3}$");
Matcher sinMatcher = sinPattern.matcher(sin);
System.out.println("SIN format valid: " + sinMatcher.matches());
Heads up: This only checks formatting. For true validation, you'll also want to implement a checksum (like the Luhn algorithm), as format alone doesn’t guarantee a legitimate SIN.
How do I validate a US Social Security Number (SSN) format using a regular expression?
If you need to check whether a string follows the standard US Social Security Number (SSN) format, a regular expression does the trick. While it won’t confirm the SSN is officially issued or valid, it does make sure the basic numeric dash pattern is correct.
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String ssn = "123-45-6789";
Pattern ssnPattern = Pattern.compile("^\\d{3}-?\\d{2}-?\\d{4}$");
Matcher matcher = ssnPattern.matcher(ssn);
System.out.println("SSN Format Valid: " + matcher.matches());
}
}
This pattern accepts both 123-45-6789
and 123456789
as valid formats, matching three digits, optional dash, two digits, optional dash, and four digits, just as expected for US SSNs.
Removing HTML Tags from a String
Ever need to clean up some text by removing all those pesky HTML tags? Regular expressions make this task a breeze.
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String html = "Hello, strongworldstrong!";
Pattern pattern = Pattern.compile("<[^>]+>");
Matcher matcher = pattern.matcher(html);
String cleaned = matcher.replaceAll("");
System.out.println("Text without HTML tags: " + cleaned);
}
}
This pattern <[^>]+>
will match any HTML tag, allowing you to strip tags while leaving the inner text untouched.
Extracting the Filename from a Windows Path
Want to grab just the filename from a full Windows file path? Since Windows paths use the backslash () as a separator, you can use a regular expression to find everything after the final backslash. Here’s how you do it:
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String path = "C:\Users\Bob\Documents\presentation_final.pptx"; Pattern pattern = Pattern.compile("[^\\]+$"); Matcher matcher = pattern.matcher(path); if (matcher.find()) { System.out.println("Filename: " + matcher.group()); } } }
This regular expression, , matches the last sequence of characters that aren't backslashes—just what you want for a filename. Keep in mind: there’s nothing stopping a directory from looking like a file (or vice versa), especially if you’re working with extensionless files. But, in general, this handy trick works wonders for most practical file-path cases.
Validate Feet and Inches Notation
Need to make sure a string like 6'2"
or 5'11"
really matches the classic feet-and-inches format (as seen in NBA player stats or your driver’s license)? Here’s a regular expression for that format:
^\\d+'(\\d1[01]
The part before the apostrophe matches one or more digits (the feet).
After the apostrophe, it allows a single digit 0–9, or 10 or 11 (the inches).
Ends with a double quote.
So, 0'0"
, 6'11"
, and even 12456'11"
are fair game. Copy this pattern for your next height validator and make those measurements count.
How can I remove all blank lines from a string using a regular expression?
Need to tidy up a string by stripping out all those pesky blank lines? You can do this easily with a regular expression. Here’s how you’d do it in Java:
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String messyText = "Line one.Line two after blanks.Line three."; // This regex targets any line that's empty or only whitespace, including Windows or Unix line endings. String cleaned = messyText.replaceAll("(?m)^\s*$[]+", ""); System.out.println(cleaned); } }
Explanation:
enables multiline mode, so and match start and end of lines, not just the start/end of the string.
matches lines containing only whitespace.
ensures any trailing line breaks are included and removed.
Now your string is as neat as a freshly vacuumed carpet—no blank lines in sight!
How do I validate date strings using regular expressions, and what are some limitations?
Don’t use regex to parse structured data such as XML, JSON, or HTML. Always use dedicated parsers for these use cases.
While regex is a powerful tool for matching patterns, it’s important to remember its limitations—especially when it comes to validating complex data like dates. Regular expressions can help ensure a date string follows the correct format (for example, yyyy-mm-dd
or mm/dd/yyyy
), but they cannot reliably validate whether a date is actually valid (think leap years, or April 31st). For truly robust validation, always use purpose-built date libraries or functions in your language of choice.
Examples of date format validation with regex:
ISO format (
yyyy-mm-dd
):^[0-9]{4}-(((0[13578](1012))-(0[1-9][1-2][0-9]3[0-1]))(02-(0[1-9][1-2][0-9]))((0[469]11)-(0[1-9][1-2][0-9]30)))$
ISO format with consistent separators (
-
,/
,.
, or space):^[0-9]{4}([- /.])(((0[13578](1012))\1(0[1-9][1-2][0-9]3[0-1]))(02\1(0[1-9][1-2][0-9]))((0[469]11)\1(0[1-9][1-2][0-9]30)))$
US format (
mm/dd/yyyy
):^(((0[13578](1012))/(0[1-9][1-2][0-9]3[0-1]))(02/(0[1-9][1-2][0-9]))((0[469]11)/(0[1-9][1-2][0-9]30)))/[0-9]{4}$
24-hour time (
HH:MM
):^(20212223[01]\d\d)((:[0-5]\d){1,2})$
These patterns can help catch obvious typos in date and time input, but don’t expect them to catch every invalid date—like “February 30th.” For that, trust your programming language’s date handling capabilities rather than stretching regex beyond its comfort zone.
How can I check for alphanumeric values using a regular expression?
Character Classes
[abc]
: Matches any one character: eithera
,b
, orc
.[^abc]
: Matches any character excepta
,b
, orc
. The caret^
negates the set.[a-zA-Z]
: Specifies a range, matches any uppercase or lowercase letter from a to z.
Common example:
To match any single alphanumeric character, you might use [a-zA-Z0-9]
. This is useful for validation patterns where you want to ensure input contains only letters and numbers.
How to Match Alphanumeric Strings
If you want to check that an entire string is strictly alphanumeric (letters and numbers only, with no spaces or special characters), use:
^[a-zA-Z0-9]
This pattern ensures the string starts (^
) and ends ($
) with one or more (+
) alphanumeric characters—no underscores, spaces, or symbols allowed.
Note: The character class
\w
(see below) also matches the underscore_
, so for strict alphanumeric-only validation, prefer[a-zA-Z0-9]
.
Predefined Character Classes
\d
: Matches any digit character; equivalent to[0-9]
.\D
: Matches any non-digit character; equivalent to[^0-9]
.\s
: Matches any whitespace character (space, tab, newline).\S
: Matches any non-whitespace character.\w
: Matches any word character (letters, digits, or underscore); equivalent to[a-zA-Z0-9_]
.\W
: Matches any character that is not a word character.
Use these shortcuts for cleaner regex patterns, especially when working with common text processing tasks like extracting numbers, validating usernames, or skipping whitespace.
Emulating DOTALL Behavior in JavaScript
You might find yourself running into an oddity: in most programming languages, the DOTALL flag (often /s
or similar) allows the .
in a regex to match absolutely anything—including line breaks. JavaScript, historically, kept .
from ever crossing newline boundaries, forcing you to get clever.
What’s the workaround?
If you're working in an environment where the DOTALL flag isn't supported (like some older JavaScript engines), you can mimic this all-consuming behavior by swapping out your lone .
for [\s\S]
. This character set means: “match anything that is a whitespace character (\s
) or not a whitespace character (\S
)”—effectively, every character in existence, including newlines.
Example:
Instead of:
/abc.def/ // Fails to match 'abcdef'
Use:
/abc[\s\S]def/ // Matches 'abcdef'
This small but mighty pattern lets your regular expressions tear right through line breaks, making them as greedy as DOTALL in other languages.
Important Tips
Always escape regex characters twice in Java (e.g., \\. to match a literal dot).
Prefer non-capturing groups unless you need references.
Avoid regex for parsing structured formats like JSON, HTML, or XML—use parsers.
Use Pattern.compile() once to reuse compiled patterns for better performance.
Use [\s\S] instead of . for multiline matching when DOTALL mode is needed.
Bonus: Example Code Snippet
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String email = "test@example.com"; Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); Matcher matcher = pattern.matcher(email); System.out.println("Email valid: " + matcher.matches()); } }
Test More Regex Patterns in Java:
Want to test in a different language? Try our:
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Java RegEx Tester
Search...
⌘K
Java RegEx Tester
Search...
⌘K


Java RegEx Tester
Java RegEx Tester
Test and debug Java regular expressions instantly using the Qodex Java RegEx Tester, powered by the java.util.regex engine. Get real-time feedback with match highlights, capture groups, and syntax error detection—making it ideal for tasks like email validation, password matching, and pattern-based string parsing.
Whether you’re building login forms, input validators, or custom parsers, this tool streamlines your Java regex workflow. For comprehensive testing, pair it with the Email Generator, UUID Generator, or Password Generator to generate realistic test inputs.
Fine-tune specific fields with our Email Regex Java Validator or Phone Number Regex Java Validator to ensure your patterns are both precise and production-ready.
[A-Z]
: uppercase letters[a-z]
: lowercase letters[0-9]
: digits\.
: a literal dot+
: one or more of the preceding*
: zero or more of the preceding?
: optional (zero or one)^
: start of string$
: end of string
Test your APIs today!
Write in plain English — Qodex turns it into secure, ready-to-run tests.
Java RegEx Tester - Documentation
Java Regex Tester
The Java Regex Tester by Qodex helps developers write, test, and debug regular expressions in real time using Java’s java.util.regex package. It supports instant pattern testing for emails, passwords, phone numbers, dates, credit cards, and more.
You can view live match results, capture groups, and syntax feedback instantly—making it easy to refine your regex before using it in Java code.
How to Use:
Enter your regular expression.
Provide a test string.
Instantly see highlighted matches and capture groups.
Need test inputs? Try our:
Java Regex Syntax Essentials
Meta characters
.
: Matches any single character except newline characters (``).
Commonly used to represent any wildcard character.^
: Anchors the match at the beginning of a line or string.
Example:^abc
matchesabc
only if it’s at the start.$
: Anchors the match at the end of a line or string.
Example:xyz$
matchesxyz
only at the end.``: Acts as a logical OR operator.
Example:catdog
matches either cat or dog. Useful for alternatives.
Character Classes
[abc]
: Matches any one character: eithera
,b
, orc
.[^abc]
: Matches any character excepta
,b
, orc
. The caret^
negates the set.[a-zA-Z]
: Specifies a range, matches any uppercase or lowercase letter from a to z.
Predefined Character Classes
\d
: Matches any digit character; equivalent to[0-9]
.\D
: Matches any non-digit character; equivalent to[^0-9]
.\s
: Matches any whitespace character (space, tab, newline).\S
: Matches any non-whitespace character.\w
: Matches any word character (letters, digits, or underscore); equivalent to[a-zA-Z0-9_]
.\W
: Matches any character that is not a word character.
Quantifiers
*
: Matches the preceding element zero or more times.
Example:lo*l
matchesll
,lol
,lool
, etc.+
: Matches one or more occurrences.
Example:lo+l
matcheslol
,lool
, but notll
.?
: Matches zero or one occurrence. Also makes quantifiers lazy when placed after them
Example:*?
{n}
: Matches exactly n occurrences.
Example:a{3}
matchesaaa
.{n,}
: Matches n or more occurrences.
Example:a{2,}
matchesaa
,aaa
,aaaa
, etc.{n,m}
: Matches between n and m occurrences.
Example:a{2,4}
matchesaa
,aaa
, oraaaa
.
Groups and Capturing
(abc)
: Captures and groups the match forabc
. This can be reused with backreferences.(?:abc)
: Groupsabc
without capturing it. Useful for applying quantifiers or alternation without creating references.(?i)abc
: Enables case-insensitive matching for the group. Matchesabc
,ABC
,AbC
, etc.\b
: A word boundary.\B
: A non-word boundary.\1
,\2
, etc.: Backreferences to captured groups.
Example:(\w+)\s\1
matches repeated words likehello hello
.
Matching a Backspace Character
[\b]
: Matches a backspace character (ASCII 0x08).
This is rarely needed in typical text processing, but can be useful when working with legacy data or control characters. Note: in most regular expression dialects, \b
by itself refers to a word boundary. When placed inside square brackets ([...]
), it specifically targets the backspace control character.
Logical Assertions (Lookaheads & Lookbehinds)
(?=...)
: Positive lookahead. Ensures what follows the current position matches the pattern inside.
Example:\d(?=px)
matches a digit only if it’s followed bypx
.(?!...)
: Negative lookahead. Ensures the following characters do not match the pattern.
Example:foo(?!bar)
matchesfoo
only if it’s not followed bybar
.(?<=...)
: Positive lookbehind. Ensures that what precedes the current position matches the pattern.
Example:(?<=@)\w+
matches the username after an@
.(?<!...)
: Negative lookbehind. Ensures that what precedes is not a match.
Example:(?<!(https:))//
matches//
not preceded byhttps:
.
Greedy vs Lazy Quantifiers
*?
: Matches as few as possible, zero or more times.+?
: Matches as few as possible, one or more times.??
: Matches as few as possible, zero or one time.{n}?
: Matches exactly n times, but tries to do it minimally.{n,}?
: Matches at least n times, but lazily.{n,m}?
: Matches between n and m times, choosing the smallest match possible.
Lazy quantifiers are useful when you’re trying to avoid consuming too much text—especially helpful for nested tags or repeated delimiters.
Unicode Support
\p{L}
: Matches any kind of letter from any language.\p{N}
: Matches any kind of numeric character.\p{IsGreek}
: Matches any character in the Greek Unicode block.\P{...}
: The inverse of\p{...}
. For example,\P{L}
matches any non-letter character.
Unicode properties allow your regex to work globally—great for international applications.
Common Patterns for Number Validation
Regular expressions are invaluable for validating and parsing numbers of various formats. Here are some frequently used patterns for number validation in Java regex:
Positive integers of undefined length
^\d+$
Matches any positive integer (e.g., 123
, 987654
).
Positive integers of maximum length (10 in this example)
^\d{1,10}$
Ensures the integer has up to 10 digits.
Positive integers of fixed length (5 in this example)
^\d{5}$
Matches exactly 5 digits.
Negative integers of undefined length
^-\d+$
Matches any negative integer (e.g., -123
, -45678
).
Negative integers of maximum length (10 in this example)
^-\d{1,10}$
Negative integer up to 10 digits.
Negative integers of fixed length (5 in this example)
^-\d{5}$
Exactly 5 digits, negative.
Integers of undefined length (positive or negative)
^-?\d+$
Matches either positive or negative integers.
Integers of maximum length (10 in this example)
^-?\d{1,10}$
Positive or negative integer up to 10 digits.
Integers of fixed length (5 in this example)
^-?\d{5}$
Exactly 5 digits, with optional negative sign.
Numbers with or without decimals
^-?\d*\.{0,1}\d+$
Matches numbers such as 1234
, -56.78
, .25
, or 0.123
.
Numbers with 2 decimals
^-?\d*\.\d{2}$
Ensures exactly two decimal places (e.g., 42.00
, -3.14
).
Currency numbers with thousands separators, optional decimals, and optional symbol
^$?\-?([1-9]{1}[0-9]{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))$^\-?$?([1-9]{1}\d{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))$^\($?([1-9]{1}\d{0,2}(,\d{3})*(\.\d{0,2})?[1-9]{1}\d{0,}(\.\d{0,2})?0(\.\d{0,2})?(\.\d{1,2}))\)$
Covers a wide range of currency inputs including optional dollar sign, commas for thousands, and up to two decimals.
Percentage values from 0 to 100, with up to 2 decimals and an optional % sign
^-?[0-9]{0,2}(\.[0-9]{1,2})?%?$^-?(100)(\.[0]{1,2})?%?$
Matches 0
, 0.00
, 100
, 99.99%
, and similar forms.
These patterns, combined with the core syntax above, equip you to validate and parse most numeric formats encountered in everyday Java development—whether it’s user input, API payloads, or data files.
Common Java Regex Examples
Email Validation
Use with Email Regex Java Validator
Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
Strong Password Check
Test using Password Regex Java Validator.
"(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}"
Phone Number Formats
Covers (123) 456-7890, 1234567890, 123-456-7890
Pattern.compile("^(\\d{10}|\\(\\d{3}\\)[\\s.-]?\\d{3}[\\s.-]\\d{4}|\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4})$")
Validating US and Canadian Phone Numbers
Looking to verify North American phone numbers with Java RegEx? There are several formats users tend to enter, such as:
999-999-9999
(999) 999-9999
9999999999
A flexible pattern can help catch these common variations. Here’s how you can implement it:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String[] phones = {
"123-456-7890",
"(123) 456-7890",
"1234567890",
"123.456.7890",
"123 456 7890"
};
Pattern phonePattern = Pattern.compile("^(\\d{10}(\\(?\\d{3}\\)?[ .-]?\\d{3}[ .-]\\d{4}))$");
for (String phone : phones) {
Matcher matcher = phonePattern.matcher(phone);
System.out.println(phone + " Valid: " + matcher.matches());
}
}
}
This approach accommodates the typical separators—spaces, dashes, or dots—and even an optional area code in parentheses. Adjust as needed if your project requires stricter formatting rules!
Credit Card Pattern Matching
Use Credit Card Regex Java Validator + Luhn check for full validation.
Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$") // VISA
Date Formats (ISO / US)
Regex checks format only—use Java date libraries for real validation.
For more thorough validation—including leap years, months with 30 vs. 31 days, and so on—consider using Java’s built-in or libraries like Apache Commons Validator. Regex is your first line of defense, but not your only one!
"\\d{4}-\\d{2}-\\d{2}" // ISO "\\d{2}/\\d{2}/\\d{4}" // US MM/DD/YYYY
Extract Filename from Windows Path
Pattern.compile("[^\\\\]+$");
IPv4 Address Validation
Want to ensure a string is a valid IPv4 address? The regular expression below checks that each number (octet) falls between 0 and 255, blocking out values like 999.999.999.999. Here’s how you can validate an IP address in Java:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String ip = "192.168.0.1";
String regex = "^(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)\\." +
"(?:25[0-5]2[0-4][0-9][01]?\\d\\d?)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ip);
System.out.println("IP Valid: " + matcher.matches());
}
}
Tips:
To check for an IPv4 address inside a larger text, you can remove the
^
and$
anchors and use word boundaries like\\b
.Each octet is checked to be between 0 and 255, preventing invalid versions such as 300.400.500.600.
This approach is handy for input validation in networking tools, login forms, or whenever you need to be sure you’re dealing with a proper IPv4 address.
Validating 24-hour Time Format (HH:MM)
Need to check if a string is a properly formatted time, like "14:45" or "09:02"? You can handle this with a regular expression that matches 24-hour time in the HH:MM format.
Here's a quick Java snippet for validating time strings:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String time = "23:59";
Pattern pattern = Pattern.compile("^([01]\\d2[0-3]):[0-5]\\d$");
Matcher matcher = pattern.matcher(time);
System.out.println("Time Valid: " + matcher.matches());
}
}
How this pattern works:
([01]\\d2[0-3])
ensures hours are between 00 and 23.:[0-5]\\d
ensures minutes are between 00 and 59.
Give it a spin. Try plugging in values like "00:00", "12:30", or "24:00" (which should fail) to see if your validation logic holds up.
Validate Hex Colors
Ever wanted to make sure that hex color code you grabbed from Photoshop or Figma is actually legit? A simple regex can help you verify both the short (3-digit) and long (6-digit) hex codes, with or without that trusty leading .
java import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String[] colors = { "#1a2B3c", "123", "#ABCDEF", "#zzz", "FFF0A" }; Pattern hexPattern = Pattern.compile("^#?([a-fA-F0-9]{6}[a-fA-F0-9]{3})$"); for (String color : colors) { Matcher matcher = hexPattern.matcher(color); System.out.println(color + " is valid hex: " + matcher.matches()); } } }
This regex checks if a string starts with an optional , followed by either exactly 3 or 6 hexadecimal digits. It’s case-insensitive so you don’t have to worry about uppercase vs. Lowercase.
SIN / SSN / ZIP Code Patterns
Check formatting only. Use:
^\d{3}-\d{2}-\d{4}$ for SSN
^\d{5}(-\d{4})?$ for ZIP +4
How do I validate a US ZIP code or ZIP+4 format using a regular expression?
Need to make sure your ZIP code input measures up to USPS standards? US postal codes come in two flavors: the classic five-digit version and the fancier ZIP+4, which tacks on a hyphen and four more digits.
Here’s how you can check for both formats using Java regular expressions:
Just the basics:
Five digits, and only five:
^\d{5}$
ZIP+4 (going the extra mile):
Five digits, optionally followed by a hyphen and four more digits:
^\d{5}(-\d{4})?$
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String zip = "90210-1234";
Pattern zipPattern = Pattern.compile("^\\d{5}(-\\d{4})?$");
Matcher matcher = zipPattern.matcher(zip);
System.out.println("ZIP Valid: " + matcher.matches());
}
}
Plug in your favorite ZIP or ZIP+4 and see if it passes muster!
Canadian Postal Code Validation
Want to check if a string is a valid Canadian postal code? Their format follows the pattern A1B 2C3
—alternating letters and digits, with an optional space in the middle (but don't expect any Z’s, D’s, or U’s—Canada Post skips those).
Here's a Java snippet to get you started:
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String postalCode = "K1A 0B1";
Pattern pattern = Pattern.compile("^[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(postalCode);
System.out.println("Canadian Postal Code Valid: " + matcher.matches());
}
}
This regular expression ensures the code matches the required format and only accepts valid starting letters. Give it a try with your favorite Toronto or Vancouver postal codes!
How do I validate a Canadian Social Insurance Number (SIN) format using a regular expression?
If you've ever needed to check if a string fits the Canadian SIN pattern, regular expressions have your back. This regex tolerates common SIN variations like 123456789
, 123-456-789
, or 123 456 789
(just make sure the separators are consistent throughout):
String sin = "123-456-789";
Pattern sinPattern = Pattern.compile("^\\d{3}([\\s-])?\\d{3}\\1\\d{3}$");
Matcher sinMatcher = sinPattern.matcher(sin);
System.out.println("SIN format valid: " + sinMatcher.matches());
Heads up: This only checks formatting. For true validation, you'll also want to implement a checksum (like the Luhn algorithm), as format alone doesn’t guarantee a legitimate SIN.
How do I validate a US Social Security Number (SSN) format using a regular expression?
If you need to check whether a string follows the standard US Social Security Number (SSN) format, a regular expression does the trick. While it won’t confirm the SSN is officially issued or valid, it does make sure the basic numeric dash pattern is correct.
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String ssn = "123-45-6789";
Pattern ssnPattern = Pattern.compile("^\\d{3}-?\\d{2}-?\\d{4}$");
Matcher matcher = ssnPattern.matcher(ssn);
System.out.println("SSN Format Valid: " + matcher.matches());
}
}
This pattern accepts both 123-45-6789
and 123456789
as valid formats, matching three digits, optional dash, two digits, optional dash, and four digits, just as expected for US SSNs.
Removing HTML Tags from a String
Ever need to clean up some text by removing all those pesky HTML tags? Regular expressions make this task a breeze.
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String html = "Hello, strongworldstrong!";
Pattern pattern = Pattern.compile("<[^>]+>");
Matcher matcher = pattern.matcher(html);
String cleaned = matcher.replaceAll("");
System.out.println("Text without HTML tags: " + cleaned);
}
}
This pattern <[^>]+>
will match any HTML tag, allowing you to strip tags while leaving the inner text untouched.
Extracting the Filename from a Windows Path
Want to grab just the filename from a full Windows file path? Since Windows paths use the backslash () as a separator, you can use a regular expression to find everything after the final backslash. Here’s how you do it:
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String path = "C:\Users\Bob\Documents\presentation_final.pptx"; Pattern pattern = Pattern.compile("[^\\]+$"); Matcher matcher = pattern.matcher(path); if (matcher.find()) { System.out.println("Filename: " + matcher.group()); } } }
This regular expression, , matches the last sequence of characters that aren't backslashes—just what you want for a filename. Keep in mind: there’s nothing stopping a directory from looking like a file (or vice versa), especially if you’re working with extensionless files. But, in general, this handy trick works wonders for most practical file-path cases.
Validate Feet and Inches Notation
Need to make sure a string like 6'2"
or 5'11"
really matches the classic feet-and-inches format (as seen in NBA player stats or your driver’s license)? Here’s a regular expression for that format:
^\\d+'(\\d1[01]
The part before the apostrophe matches one or more digits (the feet).
After the apostrophe, it allows a single digit 0–9, or 10 or 11 (the inches).
Ends with a double quote.
So, 0'0"
, 6'11"
, and even 12456'11"
are fair game. Copy this pattern for your next height validator and make those measurements count.
How can I remove all blank lines from a string using a regular expression?
Need to tidy up a string by stripping out all those pesky blank lines? You can do this easily with a regular expression. Here’s how you’d do it in Java:
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String messyText = "Line one.Line two after blanks.Line three."; // This regex targets any line that's empty or only whitespace, including Windows or Unix line endings. String cleaned = messyText.replaceAll("(?m)^\s*$[]+", ""); System.out.println(cleaned); } }
Explanation:
enables multiline mode, so and match start and end of lines, not just the start/end of the string.
matches lines containing only whitespace.
ensures any trailing line breaks are included and removed.
Now your string is as neat as a freshly vacuumed carpet—no blank lines in sight!
How do I validate date strings using regular expressions, and what are some limitations?
Don’t use regex to parse structured data such as XML, JSON, or HTML. Always use dedicated parsers for these use cases.
While regex is a powerful tool for matching patterns, it’s important to remember its limitations—especially when it comes to validating complex data like dates. Regular expressions can help ensure a date string follows the correct format (for example, yyyy-mm-dd
or mm/dd/yyyy
), but they cannot reliably validate whether a date is actually valid (think leap years, or April 31st). For truly robust validation, always use purpose-built date libraries or functions in your language of choice.
Examples of date format validation with regex:
ISO format (
yyyy-mm-dd
):^[0-9]{4}-(((0[13578](1012))-(0[1-9][1-2][0-9]3[0-1]))(02-(0[1-9][1-2][0-9]))((0[469]11)-(0[1-9][1-2][0-9]30)))$
ISO format with consistent separators (
-
,/
,.
, or space):^[0-9]{4}([- /.])(((0[13578](1012))\1(0[1-9][1-2][0-9]3[0-1]))(02\1(0[1-9][1-2][0-9]))((0[469]11)\1(0[1-9][1-2][0-9]30)))$
US format (
mm/dd/yyyy
):^(((0[13578](1012))/(0[1-9][1-2][0-9]3[0-1]))(02/(0[1-9][1-2][0-9]))((0[469]11)/(0[1-9][1-2][0-9]30)))/[0-9]{4}$
24-hour time (
HH:MM
):^(20212223[01]\d\d)((:[0-5]\d){1,2})$
These patterns can help catch obvious typos in date and time input, but don’t expect them to catch every invalid date—like “February 30th.” For that, trust your programming language’s date handling capabilities rather than stretching regex beyond its comfort zone.
How can I check for alphanumeric values using a regular expression?
Character Classes
[abc]
: Matches any one character: eithera
,b
, orc
.[^abc]
: Matches any character excepta
,b
, orc
. The caret^
negates the set.[a-zA-Z]
: Specifies a range, matches any uppercase or lowercase letter from a to z.
Common example:
To match any single alphanumeric character, you might use [a-zA-Z0-9]
. This is useful for validation patterns where you want to ensure input contains only letters and numbers.
How to Match Alphanumeric Strings
If you want to check that an entire string is strictly alphanumeric (letters and numbers only, with no spaces or special characters), use:
^[a-zA-Z0-9]
This pattern ensures the string starts (^
) and ends ($
) with one or more (+
) alphanumeric characters—no underscores, spaces, or symbols allowed.
Note: The character class
\w
(see below) also matches the underscore_
, so for strict alphanumeric-only validation, prefer[a-zA-Z0-9]
.
Predefined Character Classes
\d
: Matches any digit character; equivalent to[0-9]
.\D
: Matches any non-digit character; equivalent to[^0-9]
.\s
: Matches any whitespace character (space, tab, newline).\S
: Matches any non-whitespace character.\w
: Matches any word character (letters, digits, or underscore); equivalent to[a-zA-Z0-9_]
.\W
: Matches any character that is not a word character.
Use these shortcuts for cleaner regex patterns, especially when working with common text processing tasks like extracting numbers, validating usernames, or skipping whitespace.
Emulating DOTALL Behavior in JavaScript
You might find yourself running into an oddity: in most programming languages, the DOTALL flag (often /s
or similar) allows the .
in a regex to match absolutely anything—including line breaks. JavaScript, historically, kept .
from ever crossing newline boundaries, forcing you to get clever.
What’s the workaround?
If you're working in an environment where the DOTALL flag isn't supported (like some older JavaScript engines), you can mimic this all-consuming behavior by swapping out your lone .
for [\s\S]
. This character set means: “match anything that is a whitespace character (\s
) or not a whitespace character (\S
)”—effectively, every character in existence, including newlines.
Example:
Instead of:
/abc.def/ // Fails to match 'abcdef'
Use:
/abc[\s\S]def/ // Matches 'abcdef'
This small but mighty pattern lets your regular expressions tear right through line breaks, making them as greedy as DOTALL in other languages.
Important Tips
Always escape regex characters twice in Java (e.g., \\. to match a literal dot).
Prefer non-capturing groups unless you need references.
Avoid regex for parsing structured formats like JSON, HTML, or XML—use parsers.
Use Pattern.compile() once to reuse compiled patterns for better performance.
Use [\s\S] instead of . for multiline matching when DOTALL mode is needed.
Bonus: Example Code Snippet
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String email = "test@example.com"; Pattern pattern = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); Matcher matcher = pattern.matcher(email); System.out.println("Email valid: " + matcher.matches()); } }
Test More Regex Patterns in Java:
Want to test in a different language? Try our:
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex