ElChapo
ElChapo

Reputation: 228

How to delete a specific and not constant part of a string

I would like to cut this string

Dim str = "BMW{1}/X5{5}/image"

like this

Dim Brand = "BMW"
Dim idBrand= 1
Dim Model = "X5"
Dim Resource = "image"

for the / part I can easily do str.Split("/") but for the {1} I don't know if there is a special function or not.

Upvotes: 0

Views: 27

Answers (1)

James Thorpe
James Thorpe

Reputation: 32212

This is a good place to use regular expressions:

Dim str = "BMW{1}/X5{5}/image"
Dim regex as new RegEx("(?<brand>[^{]+){(?<idbrand>\d+)}\/(?<model>[^{]+){[^}]+}\/(?<resource>.*)")
Dim match = regex.Match(str)

match is now an object containing various bits of information about what it's found. Since I added named capturing groups into the regex (brand, idbrand, model and resource), you can now access those within the match object:

Dim Brand = match.Groups("brand").Value
Dim idBrand= match.Groups("idbrand").Value
Dim Model = match.Groups("model").Value
Dim Resource = match.Groups("resource").Value

There is lots of information on regex available on the internet, one resource I find useful is regex101.com, which will give you an explanation of what the regex is doing on the right hand side.

Upvotes: 2

Related Questions