繁体   English   中英

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

[英]Regex for all chars and new lines except symbols

我的任务是在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]"

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM