c# - Regex.replace 不会用开始字符替换多行文本行到 html block

标签 c# regex replace

我在多行文本中显式使用 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/

相关文章:

c# - 使用 NHibernate 将行插入数据库表而不在插入行后调用 scope_identity

c# - 通过动态 : . NET/C# 框架错误访问泛型类型成员时出现 StackOverflowException?

c# - 在 azure 上存储和使用现有数据保护 key

c# - boolean 类型

javascript - javascript中的正则表达式非捕获组

javascript - 替换 p 标签内选定的文本

c - C 语言中的replaceString()函数

python - 编写此正则表达式模式来检查这些短语的联合出现的更好、更简洁的方法?

regex - Grep for <?php 空行后

javascript删除数字输入中的重复小数点