我在多行文本中显式使用 c# 中的正则表达式替换函数时遇到问题。在这篇文章中,我有不同的行,有时在开头有特殊字符(例如:& 和 &&),这些行必须转换为例如HTML。它类似于 Markdown 转换...
示例文本如下:
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
^___________________________|
回复 \r
将光标返回到行的开头。
</b>ere an other demo text.\r
|__^
重写 <b>H
与 </b>
关于c# - Regex.replace 不会用开始字符替换多行文本行到 html block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25968273/