piplaw
piplaw

Reputation: 1

JavaScript Regular Expression to Java Regular Expression

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.

Upvotes: 0

Views: 1348

Answers (1)

RokL
RokL

Reputation: 2812

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.

Upvotes: 1

Related Questions