簡體   English   中英

正則表達式:在JavaScript源代碼中匹配'in'運算符

[英]Regex: Match 'in' operator in JavaScript source code

我正在嘗試對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中的variableName
  • myObject中的otherVarName
  • 文件中的一切變量

但由於for()塊且與var / const / let關鍵字無關,因此不匹配它們:

  • object1中的property1
  • object1中的property2
  • object1中的property3

在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM