0

Is it possible to automatically convert a Javacript regular expression to a Java regular expression? I find that it's often tedious to manually convert Java regular expressions to JavaScript regular expressions, and vice versa, so I want to find a way to automate this conversion.

For example, it would be useful to convert a regular expression like this one from JavaScript to Java regex syntax, and vice-versa:

/(I|you|me).*(d|st)(o|a)(|gger)(ing|ed)/ <-- This matches "I will stagger", "you have staggered", etc.

Are there any automated conversion tools that can convert regular expressions from Java to JavaScript, and vice-versa?

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • I think there might be several duplicates of this question here: https://www.google.com/#hl=en&output=search&sclient=psy-ab&q=translate+regular+expressions+between+different+languages&oq=translate+regular+expressions+between+different+languages&gs_l=hp.3...29865.38665.0.38784.58.34.0.0.0.0.167.1957.11j8.19.0.les%3B..0.0...1c.1.6.psy-ab.eSs8ZJxeqdI&pbx=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.43828540,d.dmg&fp=c88c58e01e24d8b1&biw=1366&bih=639. I'll try to merge each of the duplicates that I've found. – Anderson Green Mar 17 '13 at 22:08
  • Most of them are compatible with each other for the basic syntax (if you remove the delimiters and quotes when specifying regex in string). For more advanced syntax, I think the workaround has to be done by hand, since the meaning might be completely different. Sometimes, the workaround can be achieved by using other regex-**unrelated**-functions to complement the regex. – nhahtdh Mar 17 '13 at 22:15
  • This looks like a poorly written RegExp to me? Shouldn't `(|gger)` always match the "nothing"? Unless Java does groups right to left instead of left to right. The way to do an optional group would be `(gger)?`, the `?` meaning ["the preceding item is optional"](http://www.regular-expressions.info/reference.html). – Paul S. Mar 17 '13 at 22:18
  • 1
    @PaulS.: `??` is the exact alternative (same behaviour), while `?` is only an approximation to the behaviour (it will try `gger` before empty string). In this case, there will be no difference in the result, but it may produce different behaviour in general. – nhahtdh Mar 17 '13 at 22:28
  • That particular regular expression should behave identically between JavaScript and Java. (The `(|gger)` part should be replaced by just `gger` I think.) – Pointy Mar 17 '13 at 23:40
  • @PaulS. - Suppose you're trying to match `staggered`. Indeed alternation precedence moves left to right, but the empty string would backtrack on failing to match `staing` or `staed`, therefore trying the `gger` branch. So, no, the regex wouldn't _always_ match the empty string. But the empty string could be useful in matching, say, `doing`. – Andrew Cheong Mar 17 '13 at 23:42

0 Answers0