可以通过三种方式访问 JavaScript 对象属性。
someObject.propertyName
someObject['propertyName']//带单引号 '
someObject["propertyName"]//带双引号 "
方括号之间允许有空格,即 someObject[ 'propertyName' ]
或 someObject[ "propertyName"]
。
为了检测文本文件中对象 someObject
的所有属性,我编写了以下正则表达式。
Regex regex = new Regex(@"someObject\.[a-zA-Z_]+[a-zA-Z0-9_]*");
检测形式someObject.propertyName
。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*\]
或者匹配任何对象:
\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/