javascript - 正则表达式检测带括号的双引号 javascript 对象属性

标签 javascript c# regex

可以通过三种方式访问​​ JavaScript 对象属性。

  1. someObject.propertyName
  2. someObject['propertyName']//带单引号 '
  3. someObject["propertyName"]//带双引号 "

方括号之间允许有空格,即 someObject[ 'propertyName' ]someObject[ "propertyName"]

为了检测文本文件中对象 someObject 的所有属性,我编写了以下正则表达式。

  1. Regex regex = new Regex(@"someObject\.[a-zA-Z_]+[a-zA-Z0-9_]*"); 检测形式someObject.propertyName

  2. regex = new Regex(@"someObject\[[ ]*'[a-zA-Z_]+[a-zA-Z0-9_]*'[ ]*\]"); 检测 someObject['propertyName'] 形式的属性。

但是我无法为 someObject["propertyName"] 形式的属性编写正则表达式。每当我尝试在正则表达式中写入 "\" 时, Visual Studio 都会出错。

我在互联网上找到了一些正则表达式来检测双引号文本。例如this 。但我无法在正则表达式中添加 \[\],Visual Studio 给出错误。

如何检测 someObject["propertyName"] 表单的属性?

我正在使用 C# System.Text.RegularExpressions 库。

最佳答案

But I couldn't write regular expression for the properties of the form someObject["propertyName"]:

您可以使用此正则表达式:

\bsomeObject\[\s*(['"])(.+?)\1\s*\]

RegEx Demo

或者匹配任何对象:

\b\w+\[\s*(['"])(.+?)\1\s*\]

C#中,正则表达式就像

Regex regex = new Regex(@"\bsomeObject\[\s*(['""])(.+?)\1\s*]");

正则表达式分解:

\b      # word boundary
\w+     # match any word
\[      # match opening [
\s*     # match 0 or more whitespaces
(['"])  # match ' or " and capture it in group #1
(.+?)   # match 0 or more any characters
\1      # back reference to group #1 i.e. match closing ' or "
\s*     # match 0 or more whitespaces
\]      # match closing ]

关于javascript - 正则表达式检测带括号的双引号 javascript 对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676695/

相关文章:

javascript - 用另一个 div 完全覆盖溢出的 div

javascript - 如何使 scale() 函数成为最高优先级?

c# - ASP.NET 网络 API : How to authorize for static HTML content

c# - 如何动态添加 XmlInclude 属性

c# - 如何选择 LINQ 数据表连接中的所有列?

regex - 使用正则表达式的 R 子集数据集

java - 在 Java 中删除正则表达式匹配后的部分字符串

javascript - 创建系统为 3 名员工提供积分,每次我单击其中一个按钮时,我都会为所选用户提供 1 分 -

javascript - 在正则表达式中应用最大和最小限制

c# - 如何隐藏 CompareValidators 和正则表达式直到需要它们