Alex Gordon
Alex Gordon

Reputation: 60741

extracting two different substrings inside of a string

Using regex how do we extract multiple substrings inside of a string?

Suppose we have this:

resgrp/providers/Microsoft.Storage/storageAccounts/vvvvvdgdevstor","subject":"/blobServices/default/containers/coloradohhhhready/blobs/README_.._.hl7","eventType":"Microsoft.Storage.BlobCreated","eventTime":"2019-06-19T17:28:40.3136657Z","id":"604ad6c5a0145-04c4-26bsssss26a","data":{"api":"PutBlockList","clientRequestId":"aaaaaaae-4e68-95f6-c1ssssb02f"

The result I'd like is:

/coloradohhhhready/README_.._.hl7

What I've tried is:

(?i)(?<=\/containers\/)(.*)(?=\/blobs\/)(.*)(?<=\/blobs\/)(.*)(?=","eventtype)

Which yielded:

coloradohhhhready/blobs/README_.._.hl7

I would simply want to remove the /blobs/ segment inside of that string:

enter image description here

Upvotes: 0

Views: 61

Answers (3)

Emma
Emma

Reputation: 27723

My guess is that this expression,

(?:\/blobs\/)|(.*?)

would be maybe an option to start.

Demo

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163352

If you want to match it using a regex, you could use 2 capturing groups and match instead of using lookarounds what comes before, after and /blobs in the middle.

In the capturing group (/[^/]+) match a forward slash followed by matching not a /

Your values are in capturing group 1 and group 2.

(?i)(?:/containers)(/[^/]+)/blobs(/[^"/]+)(?:","eventtype")

Regex demo | .NET C# example

Upvotes: 1

npinti
npinti

Reputation: 52185

If you know you will always want to remove /blobs/, then simply replace the whole thing after with a /.

On the other hand, pasting your solution on Regex101 showed that the match of your epxression yields 3 groups, one of which is /blobs/. Thus, in your case it would be as simple as reconstructing another string by doing: "/" + Group[1].Value + "/" + Group[3].Value.

Upvotes: 2

Related Questions