Remove spaces only before and after commas

♀尐吖头ヾ 提交于 2021-02-07 20:13:32

问题


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

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