除符号外的所有字符和新行的正则表达式



我的任务是用C#编写一个解析器,将字符串转换为html代码。现在,我正在使用正则表达式解析字符串,因此,我的代码如下所示:

Regex regex = new Regex(@"n?[s=(.*)?](?:n?(.*)?n?)?[/s]n?");
MatchCollection matches = regex.Matches(CurrentPage.FAQ);
foreach (Match match in matches)
{
    <div class="slider">
        <div class="n">@match.Groups[1].Value</div>
        <div class="tt">@Html.Raw(match.Groups[2].Value.Replace("r", "<br />").Replace(" ", "&nbsp;"))</div>
    </div>
}   

问题是正则表达式n?[s=(.*)?](?:n?(.*)?n?)?[/s]n?仅在字符串看起来像时才有效。

[s=hello]This is demo text![/s]

如果文本中有新行,则表示无法验证。例如

[s=hello]
     This is demo list
          1. Hello world!
          2. List item
[/s]

我试图将我的表达式修改为 n?[s=(.*)?](?:n?((.|n)*)?n?)?[/s]n?但字符串可以包含一个或多个 [s] 项,因此它会将其验证为一个

[s=hello](BEGINING TO VALIDATE FROM HERE)This is demo text![/s]
[s=hello]
     This is demo list
          1. Hello world!
          2. List item
(TO HERE)[/s]

这就是为什么它将其验证为一个项目。

使用如下所示的负面展望,不要忘记启用 DOTALL (?s)修饰符以在您的正则表达式中制作点以匹配偶数换行符。

@"(?s)[s=([^[]]*)]((?:(?![/s]).)*)[/s]"

演示