简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM