【问题标题】:Regex: Match 'in' operator in JavaScript source code正则表达式:匹配 JavaScript 源代码中的“in”运算符
【发布时间】:2019-05-03 09:42:18
【问题描述】:

我正在尝试对 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 中的变量名
  • myObject 中的 otherVarName
  • 文档中的任何变量

但不匹配这些,因为 for() 块并且不管 var/const/let 关键字:

  • 对象 1 中的属性 1
  • 对象 1 中的属性 2
  • 对象 1 中的属性 3

在 C# 中实现此目的的正确正则表达式是什么?

【问题讨论】:

  • 你的代码有什么问题,它在哪里?

标签: c# .net regex regex-lookarounds


【解决方案1】:
// 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

【讨论】:

  • 感谢您的回答,但是我不想匹配 = 符号,还需要匹配括号中的 in 运算符,例如 const newVariable = (variableName in myObject); 我更新了我的问题以包括这些,抱歉造成混淆。
  • @brnbs 我用我认为你想要实现的目标更新了我的答案。
  • 不,我想匹配三个单词,如果中间是'in',左边是字符串或变量名,右边是变量名。如果将其放置在 for() 块中,我不想匹配,但没有必要放置在等号之后。我在我的问题中添加了更多示例,希望对您有所帮助。
  • @brnbs 我更新了我的答案,它现在满足您所有当前的要求。请将其标记为答案。如果您仍然不喜欢,请提出一个新问题。
  • 完美!感谢您的宝贵时间!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 2014-05-06
  • 2013-11-18
  • 2015-07-31
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
相关资源
最近更新 更多