Shah
Shah

Reputation: 1654

Replace text in string with delimeters using Regex

I have a string something like,

string str = "(50%silicon +20%!(20%Gold + 80%Silver)| + 30%Alumnium)";

I need a Regular Expression which would Replace the contents in between ! and | with an empty string. The result should be (50%silicon +20% + 30%Alumnium).

If the string contains something like (with nested delimiters):

string str = "(50%silicon +20%!(80%Gold + 80%Silver + 20%!(20%Iron + 80%Silver)|)|
              + 30%Alumnium)";

The result should be (50%silicon +20% + 30%Alumnium) - ignoring the nested delimiters.

I've tried the following Regex, but it doesn't ignore the nesting:

Regex.Replace(str , @"!.+?\|", "", RegexOptions.IgnoreCase);

Upvotes: 1

Views: 208

Answers (3)

undef
undef

Reputation: 445

You are using the lazy quantifier +? which will look for the smallest possible substring that matches your regex. To get the result you are looking for, you want to use the greedy quantifier + which will match the largest substring possible.

The following regex (not tested in C# because I don't have it available, but this should work for any standard regex implementation) will do what you want:

'!.+\|'

Upvotes: 5

Alex
Alex

Reputation: 8116

 Regex.Replace(str, @"!.+?\||\)\|", "", RegexOptions.IgnoreCase);

Works for both provided strings. I extended the regex with a 2nd check on ")/" to replace the leftover characters.

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148664

using System.Text.RegularExpressions;

str = Regex.Replace(str , @"!.+?\|", "", RegexOptions.IgnoreCase);

Upvotes: 2

Related Questions