我需要一些帮助,只替换我与正则表达式匹配的字符串的一部分。例如,我有以下文字:
This is some sentence
and the continuation of the sentence
我需要找到新的行字符,使其前面有一个单词并以单词开头,所以我使用以下正则表达式:
Regex rgx = new Regex("\w\n\w");
当我发现这种情况时,我想用空格替换换行符。所以输出看起来像这样:
This is some sentence and the continuation of the sentence
是否可以这样做?
更新12/11/14:
这个问题被标记为重复,但是,引用的解决方案并不完全是我想要的。如上所述,它需要是一个新行前面并以字符开头的场景。引用的解决方案只能捕获所有' \ n'字符并用空字符串替换它。
以下是我的问题的解决方案:
string input = "This is some sentence\nand the continuation of the sentence",
pattern = @"(\w)\n(\w)",
replacement = "$1 $2",
output = string.Empty;
output = Regex.Replace(input, pattern, replacement);
结果如下:
This is some sentence and the continuation of the sentence
我的解决方案受到this solution的启发。
答案 0 :(得分:0)
将琴弦分开并将其与新关节一起重新组合。你可以这样做:
string input = "This is a sentence\nand the continuation of the sentence.\n\nLet's go for\na second time.";
var rx = new Regex(@"\w(\n)\w");
var output = new StringBuilder();
int marker = 0;
var allMatches = rx.Matches(input);
foreach (var match in allMatches.Cast<Match>())
{
output.Append(input.Substring(marker, match.Groups[1].Index - marker));
output.Append(" ");
marker = match.Groups[1].Index + match.Groups[1].Length;
}
output.Append(input.Substring(marker, input.Length - marker));
Console.WriteLine(output.ToString());