Regex.replace不会将多行文本行替换为html块的起始字符
本文关键字:html 字符 文本 replace Regex 替换 | 更新日期: 2023-09-27 18:23:55
我在多行文本中显式替换c#中的regex函数时遇到问题。在本文中,我有不同的行,有时在开头有特殊的字符(例如:&和&&),这些行必须转换为例如html。它类似于降价转换。。。
示例文本如下:
This is a normal demo text.
&Here an other demo text.
And one more demo text.
&&Here will continue this text.
Bla bla blaaa...
文本应该是在用开始和结束html标签替换为以下文本之后:
This is a normal demo text.
<b>Here an other demo text.</b>
And one more demo text.
<em>Here will continue this text...</em>
Bla bla blaaa...
用于替换&和&;我创建了以下c#代码:
private string StartConvert(str text)
{
text = Regex.Replace(text, "^[&]{1}((?![&]).+)$", "<b>$1</b>", RegexOptions.Multiline);
text = Regex.Replace(text, "^[&]{2}((?![&]).+)$", "<em>$1</em>", RegexOptions.Multiline);
}
运行后,我会得到错误的以下内容:
This is a normal demo text.
</b>ere an other demo text.
And one more demo text.
</em>ere will continue this text...
Bla bla blaaa...
为什么这不能正确工作,为什么我只得到行前面的封闭标记。如果它是单行,它可以正常工作,但不能在多行中工作。
感谢您的帮助
我假设您的文件是Windows EOF编码的:'r'n
。
表达式:"^[&]{1}((?![&]).+)$"
将与&Here an other demo text.'r'n
匹配。
背面参考((?![&]).+)
将是Here an other demo text.'r
。
具有此替换字符串:<b>Here an other demo text.'r</b>
<b>Here an other demo text.'r
^___________________________|
CR 'r
将光标返回到该行的开头。
</b>ere an other demo text.'r
|__^
用</b>
重写<b>H
这不是解决方案,但我可以告诉你问题不在Regex,问题在打印文本。我看到Result字符串完全正常所以我做了这样的事情来检查
string[] strings = text.Split(' ');
foreach (var s in xa)
{
Console.WriteLine(s);
}
你可以在调试时检查字符串,它是可以的吗?