简体   繁体   English

用于替换JavaScript模式的RegEx

[英]RegEx for replacing a JavaScript pattern

I have tons of html files with expression like this: 我有大量的html文件,表达式如下:

eval('enterData.style.pixelTop=' + y);

and I want to eliminate the eval expression and just execute the code, in other words change it to: 我想消除eval表达式并只执行代码,换句话说,将其更改为:

enterData.style.pixelTop =  y;

Can anybody help me with this. 任何人都可以帮助我。 Im breaking my head trying to get a solution but i only know how to eliminate the eval with: 我试图找到一个解决方案,但我只知道如何消除eval:

Regex: eval\('(.*)'\)
Replace: $1

Im using java for regex. 我正在使用java进行正则表达式。

I'm guessing that we could capture both desired vars separately with an expression such as: 我猜我们可以用一个表达式分别捕获所需的vars ,例如:

.+'(.+?)'\s+?[+\-*]+\s+([a-z]+).+

We can surely simplify this expression, but I was not sure about other inputs that we might have. 我们当然可以简化这个表达式,但我不确定我们可能有的其他输入。

Java Java的

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = ".+'(.+?)'\\s+?[+\\-*]+\\s+([a-z]+).+";
final String string = "eval('enterData.style.pixelTop=' + y);\n"
     + "eval('enterData.style.pixelTop=' + x);";
final String subst = "$1$2;";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println(result);

Test 测试

 const regex = /.+'(.+?)'\\s+?[+\\-*]+\\s+([az]+).+/gm; const str = `eval('enterData.style.pixelTop=' + y); eval('enterData.style.pixelTop=' + x);`; const subst = `$1$2;`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log(result); 

Demo 演示

RegEx 正则表达式

If this expression wasn't desired, it can be modified/changed in regex101.com . 如果不需要此表达式,可以在regex101.com中对其进行修改/更改。

RegEx Circuit RegEx电路

jex.im visualizes regular expressions: jex.im可视化正则表达式:

在此输入图像描述

I know nothing about Javascript, but this is what I see. 我对Javascript一无所知,但这就是我所看到的。

You need to escape your ' characters and to put them in non-matching groups using :? 你需要转义你的'字符,并使用以下方法将它们放在不匹配的组中:?

Regex: eval\(((?:\')(.*)(?:\').*)\)
Replace: $1

Check out regex101 for prototyping regular expressions. 查看regex101以获取正则表达式的原型。

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

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