Remove characters between two characters

允我心安 提交于 2021-01-28 06:27:40

问题


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.


回答1:


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



回答2:


There is no need to use regex:

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


来源:https://stackoverflow.com/questions/20006135/remove-characters-between-two-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!