我有句话说
"This is my new program"
我想将其转换为
"This is my new program"
,即每个单词后的额外空格。
如何在.net中使用Regex实现此目的?
这必须是通用的。比如说,如果单词之间的空格数是4,那么它应该为5。
答案 0 :(得分:2)
string newString = Regex.Replace(originalString, @"\s+", " $0");
答案 1 :(得分:0)
为什么Regex
?为什么不对字符串本身使用Replace
方法?
答案 2 :(得分: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)
)
"
答案 3 :(得分:-1)
yourString = Regex.Replace(yourString, "\ {1}", " ")
这将用两个空格替换单个(也是唯一的)空格的每个实例。