在c#中使用正则表达式仅用下划线替换前导和尾随空格
我想用下划线数替换字符串的前导和尾随空格。
输入字符串
" New Folder "
(注意:前面有一个白色空格,这个字符串末尾有两个白色空格)
产量
我的愿望输出字符串"_New Folder__"
(输出字符串在前面有一个下划线,在末尾有两个下划线。)
一种解决方案是使用回调:
s = Regex.Replace(s, @"^\s+|\s+$", match => match.Value.Replace(' ', '_'));
或者使用环视(有点棘手):
s = Regex.Replace(s, @"(?<=^\s*)\s|\s(?=\s*$)", "_");
您也可以选择非正则表达式解决方案,但我不确定它是否相当:
StringBuilder sb = new StringBuilder(s); int length = sb.Length; for (int postion = 0; (postion < length) && (sb[postion] == ' '); postion++) sb[postion] = '_'; for (int postion = length - 1; (postion > 0) && (sb[postion] == ' '); postion--) sb[postion] = '_'; s = sb.ToString();