asulaiman
asulaiman

Reputation: 1271

Matching object property which is an object within a string using regex

For a string such as the following:

`const someConst= {
name: 'someName',
someProp: {
    somePropOfSomeProp: 'value'
}};`

How would i match the value of someProp ?

Assumptions:

I am using Javascript regex to solve this problem.

To provide more context to the type of structure we can expect for someProp. This is basically supposed to be the bindings property for angular components. So expected values could be the following:

bindings: {
someBinding: '=',
someOtherBinding: '@'
}

OR the props for bindings may not be on the same line. So they could be:

bindings: { someBinding: '=', someOtherBinding: '@' }

So basically i would need:

{
    someBinding: '=',
    someOtherBinding: '@'
}

Upvotes: 0

Views: 2147

Answers (2)

spanky
spanky

Reputation: 2870

To use a regex to obtain the specific requirements in the question, you can use this:

/(?!bindings\s*:\s*)(?:\{[^}]*\})/

Regex101 DEMO

It uses a negative lookahead on the property name and colon so that it isn't included in the result.

However, this regex assumes there can be no } character at all before the one that is used to terminate the object. So if somewhere in that object there's a string that includes a }, it will break.

In the extended discussion, you asked how to get the full object as well. This is more complicated, and is showing that using a JS parser like Esprima is very likely going to be a much better and more reliable solution.

Upvotes: 1

Pac0
Pac0

Reputation: 23174

This regex matched the whole object including the name someProp:

/someProp: {\n\s*somePropOfSomeProp\:.*\n}/g

Use parenthesis to have a capturing group that you can use to fine-tune what you want to use. For example :

/someProp: ({\n\s*somePropOfSomeProp\:.*\n})/g

Some caveat : may fail if value string contains also somePropOfSomeProp:, I haven't test enough cases. Or if value goes on several lines.

you can check at https://regex101.com/r/AE2dNJ/4

Quick explanation :

Find someProp: { followed by a newline, followed by spaces on the same line and then somePropOfSomeProp:, then everything following until newline, and then the closing bracket on the next line.

Upvotes: 0

Related Questions