简体   繁体   中英

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.

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 = "=.*?(,|$)";

There is no need to use regex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM