简体   繁体   English

删除两个字符之间的字符

[英]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. 这是我第一次使用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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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