Jos B
Jos B

Reputation: 117

Regex : Replace text between semicolons a certain amount of times

i'm a bit confused with regex, i have a line which looks like something like this :

test = "article;vendor;qty;desc;price1;price2"

and what i'm trying to do is to only get price1. I'm currently using this function :

Regex.Replace(test, @".*;[^;]*;", "");

which permit me to get price2 but I can't see how I can isolate price1.

Upvotes: 1

Views: 442

Answers (2)

Uri Y
Uri Y

Reputation: 850

Use the following regex:

(?:[^;]*;){4}([^;]*);

And replace the first match group.

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76577

Have you consider just using a String.Split() call instead to break your current semi-colon delimited string into an array :

var input = "article;vendor;qty;desc;price1;price2";
var output = input.Split(';');

And then you could simply access your value by its index :

var result = output[4]; // yields "price1"

You will only want to use a Regular Expression if there is a specific pattern that you can use to match and select exactly what you are looking for, but for delimited lists, the String.Split() method will usually make things easier (especially if there is nothing to uniquely identify the item you are trying to pull from the list).

Upvotes: 1

Related Questions