Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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: https://regexr.com/7jp5j
Thank you

>Solution :

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

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

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading