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

Regular expression to detect double quoted javascript object properties with brackets

本文关键字:javascript 对象 属性 正则表达式 检测 用于      更新时间:2023-09-26

有三种方法可以访问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中编写"'"时,都会出现错误。

我在网上找到了一些正则表达式来检测双引号文本。比如这个。但我不能在正则表达式中添加'['], visual studio给出了错误。

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

我使用c# System.Text.RegularExpressions

但是我不能为形式someObject["propertyName"]的属性写正则表达式:

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

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

RegEx演示

或匹配任何对象:

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