0

I am building an API that requires a SQL Regular expression to be converted to Java regular expression. This regex is specifically for the REGEXP keyword in MySQL.

My question is: is there any library or git-hub repo readily available to achieve this?

SQL Query:

SELECT company 
FROM business 
WHERE title REGEXP '^[ABCD]';

Input regex in MySQL: ^[ABCD] Output regex in Java: [A-D]*

I searched a lot over the internet, but could not find one to do this. Any suggestions how I can approach this.

Dhumil Agarwal
  • 856
  • 2
  • 11
  • 19

1 Answers1

1

Why do you think ^[ABCD] should be translated into [A-D]*? According to https://dev.mysql.com/doc/refman/8.0/en/regexp.html#regexp-syntax, ^ means the same as in Java, [ABCD] is a character class which can be written the same way in Java. [A-D] is also legal both in Java and MySQL regexes and has the same meaning. So the translation of ^[ABCD] is going to be... ^[ABCD].

Nobody is likely to write a library for translating between these two dialects in particular; for more general tools, see Tool to convert regex between different language syntaxes? or Free alternative to RegexBuddy.

Or you could write it yourself: the only syntax in that page which isn't supported in Java seems to be [= =], which requires you to know which collation to use. So you could write a method which finds the [= =] parts (using regex), and replaces them with the complete equivalence class according to your desired collation. This does not mean that every pattern will give the same result on every string; see "Regular Expression Compatibility Considerations" at https://dev.mysql.com/doc/refman/8.0/en/regexp.html and "Differences with Java Regular Expressions" at http://userguide.icu-project.org/strings/regexp for the kind of issues you'd need to deal with.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487