Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert mysql regex to java regex (and/or vice versa)

Tags:

java

regex

mysql

I have some regex that I need to convert from mysql to java, but they don't work when passed to String.matches().

How do I convert a mysql regex to a java regex?
Is there any APIs (built-in or third-party) to do this?

like image 951
user113454 Avatar asked Jan 06 '12 04:01

user113454


1 Answers

It's really simple. Here's the difference:

  • Java's String.matches() needs to match the whole String
  • mysql's regexp only needs to match part of the string

To convert a mysql regex into a java one, basically add ".*" to each end of the regex, or otherwise convert it from a "partial" match to a full match.

Here's some examples to demonstrate:

Java

"xyz".matches("y"); // false - only matches part of the input
"xyz".matches(".*y.*"); // true
"xyz".matches("[xyz]"); // false - only matches one char, but String is 3 chars
"xyz".matches("[xyz]+"); // true

mysql

select 'xyz' regexp 'y'; -- 1 (ie true)
select 'xyz' regexp '.*y.*'; -- 1 (ie true)
select 'xyz' regexp '[xyz]'; -- 1 (ie true)
select 'xyz' regexp '[xyz]+'; -- 1 (ie true)
like image 118
Bohemian Avatar answered Sep 22 '22 17:09

Bohemian