简体   繁体   English

JavaScript正则表达式到Java正则表达式

[英]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. 我有一小段用Javascript编写的文物代码,用于扫描网页源并查找模式。

I am migrating the functuanality to a Java program. 我正在将功能迁移到Java程序。 So, my questiong is how can I parse a JavaScript regular expression to a java one with some kind of find and replace function? 因此,我的问题是,如何使用某种查找和替换功能将JavaScript正则表达式解析为Java?

For example my JavaScript Regex currently reads (as a String) 例如,我的JavaScript正则表达式当前读取(作为字符串)

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

I found this old post on stackoverflow: 我在stackoverflow上发现了这个旧帖子:

How to convert javascript regex to safe java regex? 如何将javascript regex转换为安全的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. 但是,这似乎不够鲁棒,并且不会产生可被编译器识别的RegEx。

Remove the / at the start and /i at the end. 在开头删除/,在结尾删除/ i。 Add (?i) at the start. 在开始处添加(?i)。

Java doesn't use /expr/options format. Java不使用/expr/options格式。 /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. /expr/G将替换为\\ G边界匹配,但是在Java中,您通常只需多次调用matcher.find() ,它将自动在上一个匹配项的末尾搜索匹配项,从而使\\ G毫无意义。

Change all \\\\/ to / , forwards slashes don't need to be escaped. 将所有\\\\/更改为/ ,则不需要转义正斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM