<p>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 "5" after the end of input.</p>

[{'answer_id': 60161, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 10, 'selected': True, 'text': '<p>Since <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)" rel="noreferrer">Java 1.5, yes</a>:</p>\n\n<pre><code>Pattern.quote("$5");\n</code></pre>\n'}, {'answer_id': 60164, 'author': 'Rob Oxspring', 'author_id': 1867, 'author_profile': 'https://Stackoverflow.com/users/1867', 'pm_score': 4, 'selected': False, 'text': '<p>I think what you\'re after is <code>\\Q$5\\E</code>.  Also see <code>Pattern.quote(s)</code> introduced in Java5.</p>\n\n<p>See <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html" rel="noreferrer">Pattern</a> javadoc for details.</p>\n'}, {'answer_id': 60172, 'author': 'Pavel Feldman', 'author_id': 5507, 'author_profile': 'https://Stackoverflow.com/users/5507', 'pm_score': 7, 'selected': False, 'text': '<p>Difference between <a href="http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#quote-java.lang.String-" rel="noreferrer"><code>Pattern.quote</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html#quoteReplacement-java.lang.String-" rel="noreferrer"><code>Matcher.quoteReplacement</code></a> was not clear to me before I saw following example</p>\n\n<pre><code>s.replaceFirst(Pattern.quote("text to replace"), \n               Matcher.quoteReplacement("replacement text"));\n</code></pre>\n'}, {'answer_id': 11955201, 'author': 'Meower68', 'author_id': 251767, 'author_profile': 'https://Stackoverflow.com/users/251767', 'pm_score': 3, 'selected': False, 'text': '<p>First off, if</p>\n\n<ul>\n<li>you use replaceAll()</li>\n<li>you DON\'T use Matcher.quoteReplacement()</li>\n<li>the text to be substituted in includes a $1</li>\n</ul>\n\n<p>it won\'t put a 1 at the end.  It will look at the search regex for the first matching group and sub THAT in.  That\'s what $1, $2 or $3 means in the replacement text: matching groups from the search pattern.</p>\n\n<p>I frequently plug long strings of text into .properties files, then generate email subjects and bodies from those.  Indeed, this appears to be the default way to do i18n in Spring Framework.  I put XML tags, as placeholders, into the strings and I use replaceAll() to replace the XML tags with the values at runtime.</p>\n\n<p>I ran into an issue where a user input a dollars-and-cents figure, with a dollar sign.  replaceAll() choked on it, with the following showing up in a stracktrace:</p>\n\n<pre><code>java.lang.IndexOutOfBoundsException: No group 3\nat java.util.regex.Matcher.start(Matcher.java:374)\nat java.util.regex.Matcher.appendReplacement(Matcher.java:748)\nat java.util.regex.Matcher.replaceAll(Matcher.java:823)\nat java.lang.String.replaceAll(String.java:2201)\n</code></pre>\n\n<p>In this case, the user had entered "$3" somewhere in their input and replaceAll() went looking in the search regex for the third matching group, didn\'t find one, and puked.</p>\n\n<p>Given:</p>\n\n<pre><code>// "msg" is a string from a .properties file, containing "&lt;userInput /&gt;" among other tags\n// "userInput" is a String containing the user\'s input\n</code></pre>\n\n<p>replacing</p>\n\n<pre><code>msg = msg.replaceAll("&lt;userInput \\\\/&gt;", userInput);\n</code></pre>\n\n<p>with </p>\n\n<pre><code>msg = msg.replaceAll("&lt;userInput \\\\/&gt;", Matcher.quoteReplacement(userInput));\n</code></pre>\n\n<p>solved the problem.  The user could put in any kind of characters, including dollar signs, without issue.  It behaved exactly the way you would expect.</p>\n'}, {'answer_id': 13405612, 'author': 'Moscow Boy', 'author_id': 925098, 'author_profile': 'https://Stackoverflow.com/users/925098', 'pm_score': 3, 'selected': False, 'text': '<p>To have protected pattern you may replace all symbols with "\\\\\\\\", except digits and letters.  And after that you can put in that protected pattern your special symbols to make this pattern working not like stupid quoted text, but really like a patten, but your own.  Without user special symbols.</p>\n\n<pre><code>public class Test {\n    public static void main(String[] args) {\n        String str = "y z (111)";\n        String p1 = "x x (111)";\n        String p2 = ".* .* \\\\(111\\\\)";\n\n        p1 = escapeRE(p1);\n\n        p1 = p1.replace("x", ".*");\n\n        System.out.println( p1 + "--&gt;" + str.matches(p1) ); \n            //.*\\ .*\\ \\(111\\)--&gt;true\n        System.out.println( p2 + "--&gt;" + str.matches(p2) ); \n            //.* .* \\(111\\)--&gt;true\n    }\n\n    public static String escapeRE(String str) {\n        //Pattern escaper = Pattern.compile("([^a-zA-z0-9])");\n        //return escaper.matcher(str).replaceAll("\\\\\\\\$1");\n        return str.replaceAll("([^a-zA-Z0-9])", "\\\\\\\\$1");\n    }\n}\n</code></pre>\n'}, {'answer_id': 35991060, 'author': 'Androidme', 'author_id': 1014693, 'author_profile': 'https://Stackoverflow.com/users/1014693', 'pm_score': 5, 'selected': False, 'text': '<p>It may be too late to respond, but you can also use <code>Pattern.LITERAL</code>, which would ignore all special characters while formatting:</p>\n\n<pre><code>Pattern.compile(textToFormat, Pattern.LITERAL);\n</code></pre>\n'}, {'answer_id': 45415931, 'author': 'Adam111p', 'author_id': 3058581, 'author_profile': 'https://Stackoverflow.com/users/3058581', 'pm_score': 3, 'selected': False, 'text': '<p>Pattern.quote("blabla") works nicely.</p>\n\n<p>The Pattern.quote() works nicely. It encloses the sentence with the characters "<strong>\\Q</strong>" and "<strong>\\E</strong>", and if it does escape "\\Q" and "\\E".\nHowever, if you need to do a real regular expression escaping(or custom escaping), you can use this code:</p>\n\n<pre><code>String someText = "Some/s/wText*/,**";\nSystem.out.println(someText.replaceAll("[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]", "\\\\\\\\$0"));\n</code></pre>\n\n<p>This method returns: <em>Some/\\s/wText*/\\,**</em></p>\n\n<p>Code for example and tests:</p>\n\n<pre><code>String someText = "Some\\\\E/s/wText*/,**";\nSystem.out.println("Pattern.quote: "+ Pattern.quote(someText));\nSystem.out.println("Full escape: "+someText.replaceAll("[-\\\\[\\\\]{}()*+?.,\\\\\\\\\\\\\\\\^$|#\\\\\\\\s]", "\\\\\\\\$0"));\n</code></pre>\n'}, {'answer_id': 50990732, 'author': 'Akhil Kathi', 'author_id': 9717510, 'author_profile': 'https://Stackoverflow.com/users/9717510', 'pm_score': -1, 'selected': False, 'text': '<p>^(Negation) symbol is used to match something that is not in the character group.</p>\n\n<p>This is the link to <a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference" rel="nofollow noreferrer">Regular Expressions</a></p>\n\n<p>Here is the image info about negation:</p>\n\n<p><img src="https://i.stack.imgur.com/m5cXU.png" alt="Info about negation"></p>\n'}]
['https://Stackoverflow.com/questions/60160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2338/']