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.

1 Answer 1

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 ]
Sign up to request clarification or add additional context in comments.

4 Comments

When I try to write these regex in visual studio, it gives error. dotnetfiddle. Visual Studio doesn't compile it.
Try: Regex regex = new Regex(@"\bsomeObject\[\s*(['""])(.+?)\1\s*]");
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.