5

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?

1
  • Man ! It would be mandatory for you to post your attempts (precisely concise code snippets). Commented Jan 6, 2012 at 4:40

1 Answer 1

6

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.