Regex – get nearest match group from keyword

I have an issue with regex, I don’t know how to explain it. but maybe it’s better to use an example here: (fixing my title post are welcomed)

I have this javascript script which looks like this:

someFunction(Vo = Co(!0, {
  id: "Shape.c6e2778",
  other_attribute: "4",
  name: "Square"
}), Vo = Co(!0, {
  id: "Shape.3151b12",
  other_attribute: "3",
  name: "Triangle"

What I want to get is the shape id for shape named "Triangle" (the id should be 3151b12)

Right now my regex looks like this:

id:\s+"Shape\.([^"]+)",[\S\s]*?name: "Triangle"

But I get c6e2778 which is the id of Square not Triangle. how do I match shape id that is closest to name: "Triangle" keyword?

Hope this is clear enough.

You can what I did on:
Thank you

>Solution :

You may use this regex to get you match within a block of {...}:


RegEx DEmo

RegEx Details:

  • id:: Match text id:
  • \s0: Match 1+ white spaes
  • "Shape\.: Match text Shape.
  • ([^"]+): Match 1+ of any characters that are not " and capture in group #1
  • ",: Match text ",
  • (?:[^{}\n]*\n)*: Match 0 or more of any character that are not {, } and \n followed by a line break. Repeat this group 0 or more times.
  • \s*name:\s*: Match text name surrounded with optional whitespaces
  • "Triangle": Match text "Triangle"

Leave a Reply