在正则表达式中,如何在每个单词之间添加一个额外的空格?

发布于 2024-12-18 03:23:38 字数 257 浏览 0 评论 0原文

我有一句话说

"This is my new program"

我想将其转换为

"This  is  my  new  program"

ie,每个单词后面有额外的空格。

如何使用 .net 中的正则表达式实现此目的?

这必须是通用的。例如,如果单词之间的空格数为 4,则应将其变为 5。

I have a sentence say

"This is my new program"

I want to convert it to

"This  is  my  new  program"

i.e, extra space after every word.

How can I achieve this using Regex in .net ?

This has to be generic. Say for example if the number of spaces are 4 between words, it should make it 5.

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

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

发布评论

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

评论(4

雪花飘飘的天空 2024-12-25 03:23:38
string newString = Regex.Replace(originalString, @"\s+", " $0");
string newString = Regex.Replace(originalString, @"\s+", " $0");
猛虎独行 2024-12-25 03:23:38

为什么使用正则表达式?为什么不对字符串本身使用 Replace 方法?

Why Regex? Why don't you use Replace method on the string itself?

兰花执着 2024-12-25 03:23:38

你可以用这个。尽管我认为如果您没有其他想要保持不变的空间,@LukeH 解决方案会更好。

resultString = Regex.Replace(subjectString, @"(\b\w+\b)(?!$)", "$1 ");

说明:

"
(        # Match the regular expression below and capture its match into backreference number 1
   \b       # Assert position at a word boundary
   \w       # Match a single character that is a “word character” (letters, digits, etc.)
      +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \b       # Assert position at a word boundary
)
(?!      # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   $        # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
"

You could use this. Although I think that @LukeH solution is better if you don't have some other spaces that you want to leave untouched.

resultString = Regex.Replace(subjectString, @"(\b\w+\b)(?!$)", "$1 ");

Explanation:

"
(        # Match the regular expression below and capture its match into backreference number 1
   \b       # Assert position at a word boundary
   \w       # Match a single character that is a “word character” (letters, digits, etc.)
      +        # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \b       # Assert position at a word boundary
)
(?!      # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   $        # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
"
两仪 2024-12-25 03:23:38
yourString = Regex.Replace(yourString, "\ {1}", "  ")

这会将单个(且仅单个)空间的每个实例替换为两个空格。

yourString = Regex.Replace(yourString, "\ {1}", "  ")

This replaces each instance of a single (and only single) space with two spaces.

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