如何搜索此特定字符串格式的文本

本文关键字:字符串 格式 文本 何搜索 搜索 | 更新日期: 2023-09-27 18:15:44

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

   [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]

此外,在这里我想添加blockquote标签,以及想要在这些标签中显示此文本

"Axio发布的Orginall。单击此处">

当你点击"点击HEre"时,你会转到那个特定的帖子。所以这应该是一个超链接"26是后id

如何做到这一点?

如何搜索此特定字符串格式的文本

您可以使用正则表达式来匹配[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();
//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发布的Orginall。单击此处

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

 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('['));

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