0

I am trying to replace multiple values in a string. Because of framework constraints I need to use Regex. I have looked at this solution to loop over captures and this solution to replace multiple captures I am trying to replace multiple iterations of a group that depend on some other group.

For example, in the string

WfTarget[...] Id:28 [...] Documents [...] Id:22 [...] Id: 30

I am trying to extract the numbers 22 and 30.

Using the following Regex, I was able to extract the latest Id, and have multiple captures:

(?<start>( WfTarget))(?<grouper>( Id: (?<Wanted>([\d]+))[^ ]*)*)

With this, I am able to write a replacement string like ${grouper} and get all the iterations, but including the ID. Once I try, with wanted, I only get the last result

The problem with looping over the captures, is that this is a generic framework, and there is no way of saying on which group the looping must happen. Furthermore, the replacement string might have multiple groups to get things from. Resulting in extra non-wanted values

Edit

Input:

"WfTarget":"Status": "Active","Id": 2134,"StatusDisplay": "Version": 2, [...]"Documents": [ "Index": 0, "Id": 95, "Version": 0, "Index": 1, "Id": 42, [...]

Expected Output:

95,42
havan
  • 164
  • 2
  • 11
  • Forgot to say, the Regex posted works only when there are no extra characters between the elements (represented by [...] in the string). – havan Apr 20 '18 at 12:23
  • can you pls add input and expected output? and btw why only id 22 and 30 why not 28?? – Deepak Sharma Apr 20 '18 at 12:24
  • I updated to add input and expected value. @DeepakSharma I am ignoring 28 because that is the ID of the WfTarget element. I guess it is important to note that the number of IDs that I can have might change. It is probably very dumb trying to extract this via XPath and not through JSON, but all other cases are simple strings – havan Apr 20 '18 at 12:48
  • Use `Regex.Matches(s, @"""Id"":\s*(\d+)").Cast().Select(x=>x.Groups[1].Value)` – Wiktor Stribiżew Apr 20 '18 at 13:12
  • 1
    Unfortunately, that doesn't work for me. There is a LookBack in C# which I didn't know about and ended up using: (?<=WfTarget.*?)Id.+?(\d+) – havan Apr 20 '18 at 13:46
  • Your example input is insufficient to really determine this. Personally I'd just match the contents of one whole entry in `"Documents"`; then you can just match `"Index": \d+, "Id": (\d+), "Version": \d+`. But your given example gives no indication if this pattern is unique enough in the whole file, or if this even matches all entries in `"Documents"`. There is also no indication of the full structure of the file, with your example mixing what appear to be literal opening `[` brackets with `[...]` that seem to indicate left-out content, and no real separation between `"Documents"` entries. – Nyerguds Apr 23 '18 at 08:53

0 Answers0