Java Regex Tester

Test regular expressions written for Java (java.util.regex) — with warnings for anything that works differently there, and Java code to copy.

//g

Java regex syntax at a glance

Literal
Pattern.compile("pattern") — every backslash doubled in the string: "\\d+"
Named group
(?<name>…), back-reference \k<name>
Replacement
$1, ${name}
Flags
Pattern.CASE_INSENSITIVE, MULTILINE, DOTALL, COMMENTS, UNICODE_CHARACTER_CLASS — or inline (?i)
Find all
while (matcher.find()) { … }

What's different in Java

  • →matcher.matches() needs the whole string to match; matcher.find() looks for the pattern anywhere.
  • →Lookbehind needs a maximum length: {0,100} works, * and + don't.
  • →Possessive quantifiers (*+, ++) and atomic groups (?>…) are supported.
  • →\w and \d are ASCII unless you add Pattern.UNICODE_CHARACTER_CLASS; POSIX-style classes are written \p{Alpha}, \p{Digit}.

Frequently asked

Why does matcher.matches() return false when the text contains my pattern?

matches() succeeds only if the entire input matches. Use find() to search inside the text, or lookingAt() to match at the start.

How do I match a backslash in a Java regex?

The regex needs \\ (an escaped backslash), and each of those needs escaping in a Java string, so you write "\\\\" — four backslashes in the source.

ToolNinja