user113454
user113454

Reputation: 2373

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

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?

Upvotes: 5

Views: 1351

Answers (1)

Bohemian
Bohemian

Reputation: 425063

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)

Upvotes: 6

Related Questions