问题
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