在 C# 中使用正则表达式仅用下划线替换前导和尾随空格

发布于 2024-10-09 14:01:15 字数 255 浏览 1 评论 0原文

我只想用下划线数量替换字符串的前导和尾随空格。

输入字符串

" New Folder  "

(注:该字符串前面有一个空格,后面有两个空格)

输出

我想要的输出字符串 "_New Folder__"< /代码>
(输出字符串前面有一个下划线,后面有两个下划线。)

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

Input String

" New Folder  "

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

Output

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

長街聽風 2024-10-16 14:01:15

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

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

或使用环视(有点棘手):

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

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*$)", "_");
箜明 2024-10-16 14:01:15

您也可以选择非正则表达式解决方案,但我不确定它是否漂亮:

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();

You may also choose a non-regex solution, but I'm not sure it's pretty:

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文