Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a square bracket for Pattern compilation?

I have comma separated list of regular expressions:

.{8},[0-9],[^0-9A-Za-z ],[A-Z],[a-z] 

I have done a split on the comma. Now I'm trying to match this regex against a generated password. The problem is that Pattern.compile does not like square brackets that is not escaped.

Can some please give me a simple function that takes a string like so: [0-9] and returns the escaped string \[0-9\].

like image 317
Afamee Avatar asked Jul 16 '09 20:07

Afamee


People also ask

How do you escape a square bracket in regex?

Since regex just sees one backslash, it uses it to escape the square bracket. In regex, that will match a single closing square bracket. If you're trying to match a newline, for example though, you'd only use a single backslash. You're using the string escape pattern to insert a newline character into the string.

Does pattern compile like square brackets that are not escaped?

The problem is that Pattern.compile does not like square brackets that is not escaped. Can some please give me a simple function that takes a string like so: [0-9] and returns the escaped string \ [0-9\].

How to escape square brackets in SQL with LIKE clause?

Square brackets [], is among the wildcard operators used in SQL with the LIKE clause. It is used to match any single character within the specified range like ( [b-h]) or set ( [ghijk]). We can escape square brackets using two methods: The database can be created using CREATE command.

What are square brackets used for in SQL?

Square brackets [], is among the wildcard operators used in SQL with the LIKE clause. It is used to match any single character within the specified range like ( [b-h]) or set ( [ghijk]).


1 Answers

For some reason, the above answer didn't work for me. For those like me who come after, here is what I found.

I was expecting a single backslash to escape the bracket, however, you must use two if you have the pattern stored in a string. The first backslash escapes the second one into the string, so that what regex sees is \]. Since regex just sees one backslash, it uses it to escape the square bracket.

\\]  

In regex, that will match a single closing square bracket.

If you're trying to match a newline, for example though, you'd only use a single backslash. You're using the string escape pattern to insert a newline character into the string. Regex doesn't see \n - it sees the newline character, and matches that. You need two backslashes because it's not a string escape sequence, it's a regex escape sequence.

like image 170
Cullub Avatar answered Sep 28 '22 22:09

Cullub