从正则表达式文本中获取正则表达式字符串表示的最佳方式
Best way to get string representation of regex from regex literal
如果我这样做:
// note that 'x1f is a control character
var regex = new RegExp("'x1f");
// prints "//"
console.log(regex.toString());
如果我改为这样做:
var regex = /''x1f/;
// prints "/''x1f/"
console.log(regex.toString());
我希望能够从第二个正则表达式中获得第一个结果(//
-一个带有控制字符的字符串)。有简单的方法吗?到目前为止,我只能用一个恶心的eval
破解来做到这一点:
var regexValue = /''x1f/.toString();
let escapedLiteral = regexValue
// turn double backslashes ('') into single backslashes ('),
.replace(/''''/g, '''')
// remove the opening and closing forward slashes (/).
// this needs to be more intelligent - what if there are flags?
.slice(1, -1);
// there could be an invalid regular expression string
try {
regexValue = eval('new RegExp("' + escapedLiteral + '")').toString();
} catch (e) {
regexValue = null;
}
// should print "//"
document.writeln(regexValue);
我正在做一些JavaScript源代码解析,这种差异使事情变得很有挑战性。
首先,/''x1f/
与new RegExp("'x1f")
不同,而是new RegExp("''''x1f")
。
其次,如果你正在进行eval破解,你可以将正则表达式的字符串表示反馈给eval:
var x = /'x1f/;
console.log(eval(''+x));
第三,有很多JavaScript解析库,比如esprima、espree或babylon。我建议使用其中一个,或者至少研究它们的源代码。
为了快速避免eval黑客攻击,你可以做一些类似的事情:
var literalStr = "/abc/gi";
var m = /^'/(.*)'/([a-z]*)$/.exec(literalStr);
var regexObj = m ? new RegExp(m[1], m[2]) : null;
console.log(regexObj);
或者。。。
/'x1f/.toString().replace(/''x(..)/g,
function(a, b) {return a.replace("''x" + b, String.fromCharCode(b));}
);
相关文章:
- java.net和javascript之间正则表达式的差异
- Grunt匹配正则表达式
- 不同浏览器中的空白字符正则表达式行为
- 正则表达式在字符串中找到base64
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- 调用正则表达式匹配的函数
- 使用正则表达式评估电子邮件地址时出现性能问题
- Javascript 正则表达式 : ^[^/s/]+[a-z]{1,}[0-9]*[-_]*[^/][
- JavaScript正则表达式文本与RegExp对象
- 正则表达式只允许 x 个整数
- 使用正则表达式将输入格式设置为单字符逗号、单字符逗号等
- 改进用于验证付款金额的正则表达式
- 正则表达式与数字中的第二个点匹配
- 从正则表达式文本中获取正则表达式字符串表示的最佳方式
- 在正则表达式中指定新行数的最佳实践
- 在数组中存储 JS 正则表达式捕获组的最佳方法
- 最佳正则表达式方法
- 地址号码的最佳javascript正则表达式
- 验证用户名-最佳正则表达式
- 匹配电子邮件域部分的最佳正则表达式