【问题标题】:How to search text for this specific string format?如何搜索此特定字符串格式的文本?
【发布时间】:2016-11-01 14:52:51
【问题描述】:

我想检查一个字符串是否包含以下格式

   [QUOTE]
    Test sentence
    [/QUOTE]

如果是这样,那么我会这样做。

            string description = dr["description"].ToString();
            description = description.Replace("[QUOTE]", "<blockquote>");
            description = description.Replace("[/QUOTE]", "</blockquote>");

没关系。

但是这个呢?

[QUOTE=Axio;26]
Test sentence
[/QUOTE]

我还想在这里添加块引用标签,并希望在这些标签中显示此文本

“最初由 Axio 发布。单击此处”

当您单击“单击此处”时,您将转到该特定帖子。所以这应该是一个超链接“26是帖子ID

如何做到这一点?

【问题讨论】:

    标签: c# regex string blockquote


    【解决方案1】:

    您可以使用正则表达式匹配 [QUOTE] 中的任何内容,然后在分号上使用 Split 对其进行转换。像这样的:

            var regexPattern = @"\[QUOTE[=]{0,1}([\d\w;]*)\](.|\r|\n)*\[/QUOTE\]";
            var test1 = @"[QUOTE=Axio;26]
                Test sentence
                [/QUOTE]";
            var test2 = @"[QUOTE]
                Test sentence
                [/QUOTE]";
    
            var regex = new Regex(regexPattern);
    
            var match = regex.Match(test1);
            if (match.Success)
            {
                if (match.Groups.Count > 1) //matched [QUOTE=...]
                    match.Groups[1].Value.Split(';').ToList().ForEach(s => Console.WriteLine(s));
                else //matched [QUOTE]..
                    Console.WriteLine("Matched [QUOTE]");
            }
            else Console.WriteLine("No match"); 
            Console.Read();
    

    【讨论】:

      【解决方案2】:
      //Get the description text
      var description = "[QUOTE=Axio;26]Orginall posted by Axio. Click here[/QUOTE]";
      //Get your id
      var id = description.Substring(description.IndexOf(";") + 1, description.IndexOf("]") - (description.IndexOf(";") + 1));
      
      //replace with anchor with id and <blockquotes/>
      var editedstring = description
           .Remove(description.IndexOf("["), description.IndexOf("]") + 1)
           .Insert(0, "<blockquote><a href=\"#" + id + "\">")
           .Replace("[/QUOTE]", "</a></blockquote>");
      

      结果:

       <blockquote><a href="#26">Orginall posted by Axio. Click here</a> </blockquote>
      
      由 Axio 发布。点击这里

      【讨论】:

        【解决方案3】:

        有很多方法可以做到这一点,例如:

         string des = dr["description"].ToString().Replace("\n", "");
         string info[] = des.SubString(des.IndexOf('=') + 1, des.IndexOf(']')).Split(';');
         string name = info[0];
         string id = info[1]
         string sentence = des.SubString(des.IndexOf(']') + 1, des.LastIndexOf('['));
        

        当你得到这个时,你就知道该怎么做了。我是手写的,你可能需要自己调整(子字符串位置不确定是否需要添加/子1)。

        【讨论】:

        • 即使您添加了没有 ArgumentOutOfRange 异常的情况,您也需要减去起始索引来获取子字符串。并且可能使用第一次出现的 ']' 否则你会得到类似 [0]: "Axio" [1]: "26]Orgina"
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多