Home > OS >  Regex match last character before set of character from upper sentence
Regex match last character before set of character from upper sentence

Time:04-09

I'm trying to get the last character from a pattern like this below, the regex need to contain the set present in the name "C16P_P5_VC836" and match the last character from the first id, in this case "4" but this wont be always be a digit, it can be a letter as well.

I did try with something like this "id([\s\S]*?)C16P_P5_VC836" but this wont work since I need the info from the ID field just above the name one.

Can someone point me in the right direction, thanks!

  "id": "00000000-0000-0000-0000-000000000001",
  "id": "00000000-0000-0000-0000-00000000000F",
  "id": "00000000-0000-0000-0000-000000000004",
  "name": "C16P_P5_VC836",

CodePudding user response:

You could optionally repeat all preceding parts with "id": and then capture the last char a-z or digit before the closing double quote in the last line that starts with "id": right before the line that has "name": "C16P_P5_VC836",

(?:"id":\s*"[^"]*",)*\r?\n\s*"id":\s*"[^"]*([a-zA-Z0-9])",\r?\n\s*"name":\s*"C16P_P5_VC836",

The pattern matches:

  • (?:"id":\s*"[^"]*",)* Optionally repeat the line with "id":
  • \r?\n\s*"id":\s*"[^"]* Match the last line with "id":
  • ([a-zA-Z0-9]) Capture a single char a-z or digit in group 1
  • ", Match literally
  • \r?\n\s* Match a newline and optional whitespace chars
  • "name":\s*"C16P_P5_VC836", Match the line with C16P_P5_VC836

See a regex 101 demo.

  • Related