Reputation: 3054
I need to break this text and grab objects in a separated form.
object {
child {
}
}
object {
}
I am no regex expert, but after attempting, the best pattern I got to was something like so:
(.)*{(.|\n)*}/ig
But when applying it to the above text, it'll match it all, I can see why, but I don't know what else I could do to actually make it break the results into separate sections.
Edit:
To be more clear, in the text I provided, I'd like to have matched groups, from 'object {' to the closing '}', while including everything inside of it.
And to visualize it: Matched group #1:
object {
child {
}
}
Matched group #2:
object {
}
*Just to clarify, 'object' and 'child' are only examples, and I want the pattern to match any names, with an option to have a child with an identical name as it's parent
Upvotes: 0
Views: 57
Reputation: 45155
If I understand your question correctly, you want to match this:
object {
child {
}
}
and this:
object {
}
as two separate matches. In that case, you just need to make your quantifier non-greedy:
(.)*{(.|\n)*?}
The ?
makes the *
non-greedy, so instead of taking as much as possible, it'll take as little as possible.
Your original matches everything from the first {
to the last }
because it's greedy and that, of course, ends up grabbing everything.
The problem with the above is that it misses the last closing bracket on the first object because of nesting. You can fix this for the first level of nesting like this:
(.)*{({(.|\n)*?}|.|\n)*?}
By adding the clause {(.|\n)*?}
as another alternative you now match the nested child
correctly. But of course, the problem is that if you have another nested object then it'll be broken again!
Unfortunately, javascript's regex engine doesn't support recursion (some do), so you might need to take a different approach.
Upvotes: 2
Reputation: 67988
object\s*{(?:(?!\bobject\b)[\s\S])*}
Try this.See demo.
https://regex101.com/r/sH8aR8/16
var re = /object\s*{(?:(?!\bobject\b)[\s\S])*}/g;
var str = 'object {\n child {\n\n }\n}\nobject {\n\n}';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Upvotes: 2