问题
I am looking for a regex (?) way to remove spaces before and after commas only. Example:
((100 0, 101 0, 101 1, 100 1, 100 0) , (100.2 0.2, 100.8 0.2, 100.8 0.8, 100.2 0.8, 100.2 0.2))
Expected result:
((100 0,101 0,101 1,100 1,100 0),(100.2 0.2,100.8 0.2,100.8 0.8,100.2 0.8,100.2 0.2))
I could not yet find a satisfactory answer despite numerous searches.
回答1:
You can use the following regex:
s = Regex.Replace(s, " *, *", ",");
This searches for every comma preceded and/or followed by any number of spaces, and replaces the comma and spaces with just a comma.
Here's a demo: .NET Fiddle
回答2:
Using Regex
:
var result = Regex.Replace(
input,
@"\s*,\s*",
",");
Using string.Split
, Trim
and Join
:
var result = string.Join(",", input.Split(',').Select(s => s.Trim()).ToArray());
Split the string first, trim each part, join together again. Much faster than regular expressions (around 8x faster on my PC).
回答3:
One way would be to match @"\s*,\s*"
, and replace it with ","
:
var s = Regex.Replace(orig, @"\s*,\s*", ",");
\s
stands for "whitespace". It will replace spaces, tabs, vertical tabs, and so on. Asterisk qualifier is greedy, so the expression will match as many spaces as possible, both before and after the comma.
来源:https://stackoverflow.com/questions/33454971/remove-spaces-only-before-and-after-commas