0

I have a small piece of relic code written in Javascript that scans a web page source and looks for the pattern.

I am migrating the functuanality to a Java program. So, my questiong is how can I parse a JavaScript regular expression to a java one with some kind of find and replace function?

For example my JavaScript Regex currently reads (as a String)

RegEx = "/(\\/addthis_widget\\.(js|php)|\\.addthis\\.com\\/js\\/widget\\.(js|php))/i";

I found this old post on stackoverflow:

How to convert javascript regex to safe java regex?

which sudgests that this would do the trick:

strOutput.replace("/{{[^]*?}}/g","");

However, this does not seem robust enough and does not produce a RegEx which is recognised by the compiler.

2
  • I wonder if it would be possible to automatically generate a Java regular expression from a JavaScript regular expression. I'm not sure if there are any tools for this, though. Commented Mar 17, 2013 at 21:53
  • This question also discusses conversion of regular expressions from JavaScript to Java: stackoverflow.com/questions/8754444/… Commented Mar 17, 2013 at 21:56

1 Answer 1

1

Remove the / at the start and /i at the end. Add (?i) at the start.

Java doesn't use /expr/options format. /expr/G would be replaced by \G boundary match, but in java you generally just call matcher.find() multiple times, and it will start searching for the match at the end of previous one automatically, making \G pointless.

Change all \\/ to /, forwards slashes don't need to be escaped.

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.