Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a String from getting regex parsed in Java

In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so:

   if (T.matches(S)) ...

(note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.)

But now suppose S may have unsavory characters in it. For instance, let S = "[hi". The left square bracket is going to cause the regex to fail. Is there a function I can call to escape S so that this doesn't happen? In this particular case, I would like it to be transformed to "\[hi".

like image 299
doodaddy Avatar asked Oct 03 '08 19:10

doodaddy


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 character in regex Java?

Characters can be escaped in Java Regex in two ways which are listed as follows which we will be discussing upto depth: Using \Q and \E for escaping. Using backslash(\\) for escaping.

How do I escape a string in Java?

However, we know that the backslash character is an escape character in Java String literals as well. Therefore, we need to double the backslash character when using it to precede any character (including the \ character itself).

Do I need to escape in regex?

In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped. Some flavors only use ^ and $ as metacharacters when they are at the start or end of the regex respectively. In those flavors, no additional escaping is necessary. It's usually just best to escape them anyway.


1 Answers

String.contains does not use regex, so there isn't a problem in this case.

Where a regex is required, rather rejecting strings with regex special characters, use java.util.regex.Pattern.quote to escape them.

like image 176
Tom Hawtin - tackline Avatar answered Oct 13 '22 10:10

Tom Hawtin - tackline