简体   繁体   中英

RegEx for replacing a JavaScript pattern

I have tons of html files with expression like this:

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

and I want to eliminate the eval expression and just execute the code, in other words change it to:

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:

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

Im using java for regex.

I'm guessing that we could capture both desired vars separately with an expression such as:

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

We can surely simplify this expression, but I was not sure about other inputs that we might have.

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 .

RegEx Circuit

jex.im visualizes regular expressions:

在此输入图像描述

I know nothing about Javascript, but this is what I see.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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