I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}
Answer from Ferran Maylinch on Stack Overflow
Top answer
1 of 8
43

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}
2 of 8
41

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

🌐
Baeldung
baeldung.com › home › java › core java › guide to escaping characters in java regexps
Guide to Escaping Characters in Java RegExps | Baeldung
July 22, 2024 - In this quick test, the Pattern.quote() method is used to escape the given regex pattern and transform it into a String literal. In other words, it escapes all the metacharacters present in the regex pattern for us.
Discussions

Is there a way to avoid escaping backslashes in Java Regex?
Manish Giri is having issues with: Throughout the video, the examples using regex required escaping the \ to be interpreted as a regex, like - skills.split("\\W... More on teamtreehouse.com
🌐 teamtreehouse.com
2
October 27, 2017
regex - How to escape text for regular expression in Java? - Stack Overflow
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a & More on stackoverflow.com
🌐 stackoverflow.com
what does "\\[" mean in java?
Okay, there are a couple things: \\ actually means \ because the backslash is an escape character and needs to be escaped to be a backslash in a string. (In order to print \ you need to write System.out.println("\\"); and the same is for the regex string) [ is just the opening square brace, but again, in regex this is a special character (which normally denotes the beginning of a range of alternatives) in order to get the literal [ it needs to be escaped leading to the first 2 parts: \\[ (were you going to print this, it would look like \[ - an escaped square brace - and that is the actual regex part. * is a quantifier meaning zero or more The actual, real regex is \[* but since Java needs escaping of certain characters, it becomes the less readable \\[* that can be stored in the string. Tip: whenever you need explanations with regex, check regex101.com . Your case gives that explanation: https://i.imgur.com/0D0P6ev.png More on reddit.com
🌐 r/learnjava
3
4
November 24, 2021
What is full list of chars that require escape in 'regular' regex?
there is no "regular" regex. There's BREs (Basic Regular Expressions), ERE (Extended Regular Expressions), PCRE (Perl Compatable Regular Expressions), vim regular expressions, and dozens of variations on those. And the characters that need to be escaped depend on which flavor of regular expression you use. Which is also why the r/regex pinned post requests that you include the flavor of regex-engine because it changes the tokens available. More on reddit.com
🌐 r/regex
8
3
January 29, 2023
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 8 )
July 21, 2026 - When this flag is specified then the input string that specifies the pattern is treated as a sequence of literal characters. Metacharacters or escape sequences in the input sequence will be given no special meaning.
🌐
Abareplace
abareplace.com › blog › escape-regexp
Which special characters must be escaped in regular expressions? — Aba Search & Replace
January 8, 2022 - There is the Pattern.quote method for inserting a string into a regular expression. It surrounds the string with \Q and \E, which escapes multiple characters in Java regexes (borrowed from Perl).
🌐
JRebel
jrebel.com › blog › java-regular-expressions-cheat-sheet
Java Regular Expressions (Regex) Cheat Sheet | JRebel
July 30, 2025 - A regular character in the Java Regex syntax matches that character in the text. If you'll create a Pattern with Pattern.compile("a") it will only match only the String "a". There is also an escape character, which is the backslash "\".
Find elsewhere
🌐
DEV Community
dev.to › miguelmj › correctly-escaping-regular-expressions-27nc
Correctly escaping regular expressions - DEV Community
August 30, 2020 - There are some special characters with special meaning (their explanation is not the point of this post), and if we want to use those characters without its special meaning, we escape them by putting a backslash (\) before them. Note that this makes \ a special character too! A simple example: the regex to match exactly Count balance: 50$ will be Count balance: 50\$. What happens with is that in most languages \ is a special character for strings!
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-illustrate-escaping-characters-in-regex
Java Program to Illustrate Escaping Characters in Regex - GeeksforGeeks
September 30, 2021 - In the below source code the Regex pattern p is escaped for the dot(.) operator, whereas the pattern p1 is not escaped for dot(.). Thus the pattern p matches only with the string s whereas the pattern p1 matches with both the strings s and s1. ... /*package whatever //do not write package name here */ import java.io.*; import java.util.regex.*; class GFG { public static void main (String[] args) { String s="Geeks.forGeeks";//sample strings String s1="GeeksforGeeks"; //patterns with dot escaped Pattern p=Pattern.compile("\\."); // pattern without dot escaped Pattern p1=Pattern.compile("."); //m
🌐
Jenkov
jenkov.com › tutorials › java-regex › index.html
Java Regex - Java Regular Expressions
March 5, 2019 - The special metacharacter meaning of an escaped metacharacter is ignored - only its actual literal value (e.g. a fullstop) is used. Java regular expression syntax uses the backslash character as escape character, just like Java Strings do.
🌐
NTU Singapore
www3.ntu.edu.sg › home › ehchua › programming › howto › Regexe.html
Regular Expression (Regex) Tutorial
to escape special regex characters, e.g., \. for ., \+ for +, \* for *, \? for ?. You also need to write \\ for \ in regex to avoid ambiguity. Regex also recognizes \n for newline, \t for tab, etc. Take note that in many programming languages (C, Java, Python), backslash (\) is also used for escape sequences in string, e.g., "\n" for newline, "\t" for tab, and you also need to write "\\" for \. Consequently, to write regex pattern \\ (which matches one \) in these languages, you need to write "\\\\" (two levels of escape!!!).
🌐
Medium
medium.com › sina-ahmadi › java-regex-6e4d073aab85
Java RegEx. special characters issue in Java split… | by Sina | My journey as a software developer | Medium
June 20, 2018 - Replace all special characters using Java’s “replaceAll” method in the input string, with escaped special characters · Split on the escaped characters · The code looks like below: escapedString = nonEscapedString.replaceAll("\\*", "\\\\*"); splittedString = escapedString.split("\\*") Hope this fix would solve your issue too. Programming · Regex ·
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › RegExp › escape
RegExp.escape() - JavaScript | MDN
The first character of the string, if it's either a decimal digit (0–9) or ASCII letter (a–z, A–Z), is escaped using the \x character escape syntax. For example, RegExp.escape("foo") returns "\\x66oo" (here and after, the two backslashes in a string literal denote a single backslash ...
🌐
W3Schools
w3schools.com › java › java_strings_specchars.asp
Java Strings - Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate an error: String txt = "We are the so-called "Vikings" from the north."; The solution to avoid this problem, is to use the backslash escape character.
🌐
SSOJet
ssojet.com › escaping › regex-escaping-in-java
Regex Escaping in Java | Escaping Techniques in Programming
In Java, however, you're working within string literals, which also use the backslash as an escape character. This means you need to escape the backslash itself. For instance, to match a literal dot (.), your Java regex string becomes "\\.".
🌐
Reddit
reddit.com › r/learnjava › what does "\\[" mean in java?
r/learnjava on Reddit: what does "\\[" mean in java?
November 24, 2021 -

I understand its a type of regex and it can be used like

.replaceAll("\\[", "").replaceAll("\\]","")

to remove the square brackets from a string. eg "[yes]" becomes "yes". What does the "\\[" represent?

🌐
TutorialsPoint
tutorialspoint.com › article › java-program-to-illustrate-escaping-characters-in-regex
Java Program to Illustrate Escaping Characters in Regex
September 11, 2024 - The primary method to escape special characters in Java regular expression is by using the backslash. However, since the backslash is also an escape character in Java strings, you need to use double backslashes (\) in your regex patterns.
🌐
Esdiscuss
esdiscuss.org › topic › regexp-escape
RegExp.escape()
It is trivial to implement, but it seems to me that this functionality belongs to the language - the implementation obviously knows better which characters must be escaped, and which ones don't need to. Hello everybody. How about standardizing something like RegExp.escape() ?
🌐
Codemia
codemia.io › knowledge-hub › path › how_to_escape_text_for_regular_expression_in_java
How to escape text for regular expression in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises