【问题标题】:Extracts all sub strings between string separators in a string (C#)提取字符串中字符串分隔符之间的所有子字符串(C#)
【发布时间】:2015-08-01 16:54:42
【问题描述】:

我正在尝试解析字符串的内容以查看字符串是否包含 url,将完整的字符串转换为 html,以使字符串可点击。

我不确定是否有更智能的方法来执行此操作,但我开始尝试使用用于字符串的 Split 方法或 C# 中的 Regex.Split 创建解析器。但我找不到一个好的方法。

(它是一个 ASP.NET MVC 应用程序,所以也许有一些更聪明的方法)

我想前任。转换字符串;

"Customer office is responsible for this. Contact info can be found {link}{www.customerservice.com}{here!}{link} More info can be found {link}{www.customerservice.com/moreinfo}{here!}{link}"

进入

"Customer office is responsible for this. Contact info can be found <a href=www.customerservice.com>here!</a> More info can be found <a href=www.customerservice.com/moreinfo>here!</a>"

{link}{url}{text}{link} --> <a href=url>text</a>

谁有好的建议?我还可以更改输入字符串的格式。

【问题讨论】:

标签: c# asp.net regex string parsing


【解决方案1】:

你可以使用以下来匹配:

{link}{([^}]*)}{([^}]*)}{link}

并替换为:

<a href=$1>$2</a>

DEMO

解释:

  • {link} 匹配 {link} 字面意思
  • {([^}]*)} 匹配捕获组 1 中除 } 之外的所有字符(用于 url)
  • {([^}]*)} 匹配捕获组 2 中除 } 之外的所有字符(用于值)
  • {link} 再次匹配 {link}

【讨论】:

    【解决方案2】:

    你可以使用正则表达式

    {link}{(.*?)}{(.*?)}{link}
    

    和替换为

    <a href=\1>\2</a>
    

    Regex

    【讨论】:

      【解决方案3】:

      对于您的简单链接格式{link}{url}{text},您可以使用简单的Regex.Replace

      Regex.Replace(input, @"\{link\}\{([^}]*)\}\{([^}]*)\}", @"<a href=""$1"">$2</a>");
      

      【讨论】:

        【解决方案4】:

        这个非正则表达式的想法也可能有所帮助

        var input = "Customer office is responsible for this. Contact info can be found {link}{www.customerservice.com}{here!}{link} More info can be found {link}{www.customerservice.com/moreinfo}{here!}{link}";
        
        var output = input.Replace("{link}{", "<a href=")
                          .Replace("}{link}", "</a>")
                          .Replace("}{", ">");
        

        【讨论】:

          猜你喜欢
          • 2018-10-13
          • 1970-01-01
          • 1970-01-01
          • 2013-12-11
          • 2021-09-08
          • 2021-04-04
          • 2018-02-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多