0

There are three ways to access JavaScript Object property.

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

Spaces between the brackets, i.e., someObject[ 'propertyName' ] or someObject[ "propertyName" ], are allowed.

To detect all properties of the object someObject within a text file, I wrote the following regexes.

  1. Regex regex = new Regex(@"someObject\.[a-zA-Z_]+[a-zA-Z0-9_]*"); to detect properties of the form someObject.propertyName.

  2. regex = new Regex(@"someObject\[[ ]*'[a-zA-Z_]+[a-zA-Z0-9_]*'[ ]*\]"); to detect properties of the form someObject['propertyName'].

But I couldn't write regular expression for the properties of the form someObject["propertyName"]. Whenever I try to write " or \" within a regular expression visual studio gives error.

I found some regular expression in the internet to detect double quoted text. For example this. But I couldn't add \[ and \] in the regex, visual studio gives error.

How the properties of the form someObject["propertyName"] can be detected?

I'm using C# System.Text.RegularExpressions library.

Community
  • 1
  • 1
Rafaf Tahsin
  • 7,652
  • 4
  • 28
  • 45

1 Answers1

3

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

You can use this regex:

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

RegEx Demo

Or to match any object:

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

In C#, regex would be like

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

RegEx Breakup:

\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 ]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • When I try to write these regex in visual studio, it gives error. [dotnetfiddle](https://dotnetfiddle.net/7bo0bS). Visual Studio doesn't compile it. – Rafaf Tahsin Sep 20 '15 at 07:06
  • 1
    Try: `Regex regex = new Regex(@"\bsomeObject\[\s*(['""])(.+?)\1\s*]");` – anubhava Sep 20 '15 at 07:16
  • Thanks :D. I'll be very pleased, if you explain it to me. Why visual studio gave error? and where can I get a proper documentation. I searched for it since last night and couldn't solve it. – Rafaf Tahsin Sep 20 '15 at 07:48
  • 1
    [Se this MSDN Q&A](https://social.msdn.microsoft.com/Forums/en-US/0ef910bd-2431-4229-95dc-a5c6fe7a6af6/including-quotes-in-a-c-regex-pattern?forum=csharplanguage) – anubhava Sep 20 '15 at 08:17