【问题标题】:How to handle multiple regular expression in same string C#如何处理同一字符串中的多个正则表达式C#
【发布时间】:2016-04-28 19:59:30
【问题描述】:

我正在尝试使用正则表达式处理同一字符串中的多种不同情况。但是当我使用下面的代码时,只有最后一个表达式会起作用。所以 dobbel stars(**) 将按原样发布,但下划线(_) 将由replace()函数处理。

[HttpPost]
[ValidateInput(false)]
 public ActionResult Comment(Models.CommentModel s)
    {
        Regex fat = new Regex(@"\*\*(.*?)\*\*");
        Regex italic = new Regex(@"_(.*?)_");

       s.comment = fat.Replace(HttpUtility.HtmlEncode(s.comment), "<b>$1</b>");
       s.comment = italic.Replace(HttpUtility.HtmlEncode(s.comment), "<i>$1</i>");

       var db = new WebApplication1.Models.ApplicationDbContext();

        if (ModelState.IsValid)
        {

            if (file != null)
        {
            db.Comments.Add(s);
            db.SaveChanges();
            return RedirectToAction("Comment");
        }
        return View(s);
    }

为了减少代码量,我尝试像这样将italicfatstring 合并在一起:Regex(@"\*\*(.*?)\*\*|_(.*?)_"); 但是我还有另一个问题,Regex 怎么知道区别?

【问题讨论】:

标签: c# regex asp.net-mvc


【解决方案1】:

因为你编码相同的 html 两次

   // comment : sampletext **bold** _italic_ stuffsss

   s.comment = fat.Replace(HttpUtility.HtmlEncode(s.comment), "<b>$1</b>");
   // comment : sampletext <b>bold</b> _italic_ stuffsss

   s.comment = italic.Replace(HttpUtility.HtmlEncode(s.comment), "<i>$1</i>");
   // comment : sampletext &lt;b&gt;bold&lt;/b&gt; <i>italic</i> stuffsss

完成替换后,只需对其进行一次编码:

Regex fat = new Regex(@"\*\*(.*?)\*\*"); // btw this is called `bold` not `fat`
Regex italic = new Regex(@"_(.*?)_");

s.comment = HttpUtility.HtmlEncode(s.comment)

s.comment = fat.Replace(s.comment, "<b>$1</b>");
s.comment = italic.Replace(s.comment, "<i>$1</i>");

【讨论】:

  • 谢谢你这工作完美,我唯一需要做的改变是最后一行,它需要高于replace() 行才能工作。
  • 你是对的。实际上,它必须高于替换,因为任何尖括号都将是我们不想要的编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多