Reputation: 1645
I am working with a string that will always have "Product 1:" in it. I want to get the value of what comes after "product 1:". Here are some example of the string
Hello UserName Product 1: Alcatel Product 2: Samsung Truck: Fedex Ending: Canada
Hello UserName Product 1: NOKIA Truck: Fedex Ending: Canada
Hello UserName Product 1: Alcatel Product 2: Samsung Product 3: NOKIA Truck: Canada POST Ending: Brazil
Hello UserName Product 1: Alcatel-55 Special Product 2: Samsung Product 3: NOKIA Truck: Canada POST Ending: Brazil
Hello UserName Product 1: Samsung Galaxy S6-33 Truck: Canada POST Ending: Brazil
The string I am looking for:
I was having a little bit of luck with
sMessage.Split("Product 1:")(1).Split(":")(1)
But with above code I still get
Upvotes: 1
Views: 6602
Reputation: 24395
You could replace the undesired values with:
sMessage.Split("Product 1:")(1).Split(":")(1).Replace(" Truck", "")
You can also match the desired string with regular expressions:
(?<=Product 1: )((.*)(?= Product 2:)|(.*)(?= Truck:))
Example:
Dim regex As Regex = New Regex("(?<=Product 1: )((.*)(?= Product 2:)|(.*)(?= Truck:))")
Dim match As Match = regex.Match("Hello UserName Product 1: NOKIA Truck: Fedex Ending: Canada")
Note that if there are more delimiters than Product x
and Truck
you want to remove then you need to add those to the regular expression (or replace).
Edit
Updated the regular expression to be more generic in regards of delimiter words:
(?<=Product 1: )((.*)(?= Product 2:)|(.*?)(?= \w+:)|.*)
Now it will match on Product 2:
or any other, or no delimiter.
Edit 2
More simplifications:
(?<=Product 1: )((.*?)(?= \w+ ?(\d+)?:)|.*)
This last regular expression also matches correctly if there is a delimiter with multiple digits like Products 123:
.
Upvotes: 2
Reputation: 1254
This assumes you want the value between "Product 1:" and whatever the next "tag" happens to be, which in some cases is "Product 2:" and in other cases is "Truck:". Keep in mind that this is based only on the sample you provided - if you have other "tags" which can appear after the "Product 1:", you'll need to adjust.
The following regex will get you almost what you asked for
(?:Product 1:)(?<product>.+?)(?=(\sProduct 2:)|(\sTruck:))
Using that regex, and given your sample text, you will get capture groups named "product" as follows:
Upvotes: 0