Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape text for regular expression in Java

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.

like image 333
Matt Avatar asked Sep 12 '08 23:09

Matt


People also ask

How do you escape a string in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

How do you escape a string in Java?

Some characters preceded by a backslash ( \ ) form an escape sequence and have special meaning to the compiler. So in your case \n and \t are treated as special (newline and tab respectively). So we need to escape the backslash to make n and t treated literally.

What is the use of \\ in Java?

The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.


1 Answers

Since Java 1.5, yes:

Pattern.quote("$5"); 
like image 56
Mike Stone Avatar answered Sep 22 '22 18:09

Mike Stone