deathismyfriend
deathismyfriend

Reputation: 2192

Remove characters between two characters

I am having a problem with trying to remove text between two characters. I want to remove all text between = and ,. Here is sample code I am trying to apply this to.

    "Y = Yellow,  W = White,  B = Blue,  R = Black Out"

What i want to do is have the above change to this.

    "Y W B R"

or this but the above is prefered.

    "Y W B R = Black Out"

Here is what i am trying.

        string input = "Y = Yellow,  W = White,  B = Blue,  R = Black Out";
        string regex = "(\\=.*\\,)";
        string output = Regex.Replace(input, regex, "");

Here is what gets shown

    "Y R = Black Out"

I know i am doing something wrong. This is my first time using Regex.

Upvotes: 1

Views: 3782

Answers (2)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

There is no need to use regex:

string result = string.Join(" ", input.Split(',')
                                 .Select(p => p.Split('=')[0].Trim()));

Upvotes: 4

Jacob
Jacob

Reputation: 78848

The problem is that * is greedy with regular expressions. Therefore, everything from the first , to the last = is grabbed. Use *? to use a non-greedy match:

string regex = "=.*?,";

To get rid of the last value, you can do this:

string regex = "=.*?(,|$)";

Upvotes: 4

Related Questions