我正在尝试对 C# 中的 JavaScript 源代码进行非常简单的静态分析。我想创建一个正则表达式,它可以匹配和替换源代码中 'in' 运算符的用法。
引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
我在这方面取得了成功,但是我需要排除在“for”循环中使用“in”运算符的情况。
所以对于这个示例代码:
const oneVariable = 'property' in myObject;
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
const anotherVariable = 0 in trees;
const newVariable = variableName in myObject;
const newerVariable = (otherVarName in myObject);
console.log(whateverVariable in document);
for (var property1 in object1) {
string1 += object1[property1];
}
for (const property2 in object1) {
string1 += object1[property1];
}
for (let property3 in object1) {
string1 += object1[property1];
}
我要匹配这些:
- myObject 中的“属性”
- 0 在树上
- myObject 中的变量名
- 我对象中的其他变量名
- 文档中的任何变量
但不匹配这些,因为 for() block 并且不管 var/const/let 关键字:
- 对象 1 中的属性 1
- 对象 1 中的属性 2
- 对象 1 中的属性 3
在 C# 中实现此目的的正确正则表达式是什么?
最佳答案
// input is your Javascript code
var matches = Regex.Matches(input, @"(?<!(?:for\s?\()(?:.*)?)(\'?\w+\'?\sin\s\w+)");
var matchedInStatements = matches.Cast<Match>().Select(i => i.Value).ToList();
matchedInStatements
现在将您的所有匹配项保存为字符串。
有关解释,请查看 this .
关于c# - 正则表达式:匹配 JavaScript 源代码中的 'in' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571006/