【问题标题】:Regular expression to detect double quoted javascript object properties with brackets正则表达式检测带括号的双引号 javascript 对象属性
【发布时间】:2015-09-20 06:54:50
【问题描述】:

访问 JavaScript Object 属性的方法有三种。

  1. someObject.propertyName
  2. someObject['propertyName'] // with single quote '
  3. someObject["propertyName"] // with double quote "

括号之间允许有空格,即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 库。

【问题讨论】:

    标签: javascript c# regex


    【解决方案1】:

    但我无法为someObject["propertyName"] 形式的属性编写正则表达式:

    你可以使用这个正则表达式:

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

    RegEx Demo

    或匹配任何对象:

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

    C# 中,正则表达式就像

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

    RegEx 拆分:

    \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 ]
    

    【讨论】:

    • 当我尝试在 Visual Studio 中编写这些正则表达式时,它会出错。 dotnetfiddle。 Visual Studio 不编译它。
    • 试试:Regex regex = new Regex(@"\bsomeObject\[\s*(['""])(.+?)\1\s*]");
    • 谢谢:D。如果你给我解释一下,我会很高兴的。为什么视觉工作室给出错误?我在哪里可以获得适当的文件。我从昨晚开始搜索,无法解决。
    猜你喜欢
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    相关资源
    最近更新 更多