2011-11-25 86 views
0

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

"This is my new program" 

我想每一个字后,将其转换为

"This is my new program" 

即,额外的空间。

如何在.net中使用正则表达式来实现这个功能?

这必须是通用的。例如,如果单词之间的空格数是4,则应该使它为5.

+0

不会是一个更容易做没有正则表达式,即使用['与string.replace( “”, “”)'](HTTP ://msdn.microsoft.com/en-us/library/fk49wtc1.aspx) –

+0

@Shaw - 问题是可能存在单词之间的空格数可能是2或3或4或n的句子。我总是想添加1个额外的空间。举例来说:如果有4个空格,我想使它成为5. – GuruC

+0

这实际上是单词之间的额外空间。如果是之后,“程序”之后应该有一个空格,如果之前已经有了,那么在“这个”之前应该有一个空格。 – Vatine

回答

2
string newString = Regex.Replace(originalString, @"\s+", " $0"); 
0

为什么Regex?为什么不在字符串本身上使用Replace方法?

+0

问题是可能存在单词之间的空格数可能是2或3或4或n的句子。我总是想添加1个额外的空间。举个例子:如果有4个空格,我想让它变成5. – GuruC

+0

@abhinav:'[?!\ s] [\ s] *'匹配'?,'!'或者空白字符之一。由零个或多个空白字符组成。我不认为这就是你的意图。 –

+0

我的不好,打算做一个负面的预测。弄乱。谢谢。 – abhinav

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

这将使用两个空格替换单个(且只有一个)空间的每个实例。

+0

这不适用于我,因为它将每个实例替换为2个空格。我想在这些词语之间增加一个额外的空格! – GuruC

0

您可以使用它。尽管我认为@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) 
) 
" 
相关问题