仅更换领导和在C#中使用正则表达式结尾的空白带下划线 [英] Replace only leading and trailing whitespace with underscore using regex in c#

查看:170
本文介绍了仅更换领导和在C#中使用正则表达式结尾的空白带下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换只有开头和结尾用下划线的数字串的空白。

I want to replace only leading and trailing white space of a string by number of underscore.

输入字符串

" New Folder  "

(注:有一个在前面,在这个字符串的结尾两个白色的空间一白空间)

(Notes: There is one white space at front and two white spaces at the end of this string)

输出

我的愿望输出字符串_新建文件夹__结果
(输出字符串在其前方有一个下划线和两个下划线结尾)

My desire output string "_New Folder__"
(The output string has one underscore at the front and two underscore at the end.)

推荐答案

一个解决方案是使用一个回调:

One solution is using a callback:

s = Regex.Replace(s, @"^\s+|\s+$", match => match.Value.Replace(' ', '_'));

或使用环视(有点麻烦):

Or using lookaround (a bit trickier):

s = Regex.Replace(s, @"(?<=^\s*)\s|\s(?=\s*$)", "_");

这篇关于仅更换领导和在C#中使用正则表达式结尾的空白带下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆