I have a snippet of code like this:
{
a: {
b: 1,
c: 2,
},
d: {
e: 4,
f: 5,
},
}
I need a regex which matches the two objects a and d seperately.
First match:
a: {
b: 1,
c: 2,
},
Second match:
d: {
e: 4,
f: 5,
},
I tried this:
.+: {
([sSr]+)
},
But it greedyly matches the two objects as one match.
How do I make the expression lazy?
I tried to place the lazy operator ?
at several places. It didn’t work.
I use the text search in VS Code.
2
Answers
Thank you marchant felts, your answer leaded me to the solution:
I added the
?
in the second line after the+
. It works in VS Code.In the regex you provided, there seem to be some mismatched components compared to your code sample. In your code sample, there are no "catalog_ids" properties. Let’s modify the regex to conform to your code sample.
In order to make your regex non-greedy (or lazy), you need to employ the
?
character in the right place. To capture the JavaScript objects you mentioned, you should position the?
character just behind the+
inside your group, like(.+?)
. This means "match any character one or more times, but as few as possible".Here is a regex that should work:
Explanation:
(w+)
– matches any word character (equal to[a-zA-Z0-9_]
):s+{
– matches:
then any whitespace characterss+
, then{
[sS]*?
– matches any character (including line breaks), but as few as possible due to the?
},
– matches},
Please bear in mind that regex isn’t necessarily the best tool to parse nested structures like JSON. Depending on the language you’re working in, you may want to consider utilizing a JSON parser or similar tool instead.
As you’re employing VS Code, this regex should work fine if you ensure that the "Use Regular Expressions" and "Match Case" options are checked in the search panel. Also remember that regex in the search bar of VS Code doesn’t necessitate surrounding
/
delimiters.