winforms 如何删除标记之间的值?

qyzbxkaa  于 2023-05-07  发布在  其他
关注(0)|答案(2)|浏览(107)

我想删除标签中的值,该怎么做?突出显示的输出是我想在加载保存文件时删除的内容。

<data name="Enrolment_Exit_Verify_Message" d2p1:space="preserve"  xmlns:d2p1="http://www.w3.org/XML/1998/namespace">
<value**>**Are you sure you want to Exit without Saving?****</value>
<comment>[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]</comment>

这是我如何在标签之间读取的?我不知道如何删除标签之间的内容。

for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
            {
                string comment = oDataSet.Tables["data"].Rows[i][2].ToString();

                string font = Between(comment, "[Font]", "[/Font]");
                string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
                string commentVal = Between(comment, "[Comment]", "[/Comment]");

                string[] row = new string[] 
                {
                    oDataSet.Tables["data"].Rows[i][0].ToString(),
                    oDataSet.Tables["data"].Rows[i][1].ToString(),
                    font, 
                    datestamp, commentVal };
                Gridview_Output.Rows.Add(row);
            }
            oDataSet.Tables.Add(oDataTable);

串函数

public string Between(string STR, string FirstString, string LastString)
    {
        string FinalString;
        int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
        int Pos2 = STR.IndexOf(LastString);
        FinalString = STR.Substring(Pos1, Pos2 - Pos1);
        return FinalString;
    }
kqhtkvqz

kqhtkvqz1#

如果可以构建正则表达式,可以在between方法中使用正则表达式。Here is more info on the regex

public string Between(string STR, string FirstString, string LastString)
{
    string regularExpressionPattern1 = @"(?:\" + FirstString + @")([^[]+)\[\/" + LastString;
    Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
    MatchCollection collection = regex.Matches(STR.ToString());
    var val = string.Empty;
    foreach (Match m in collection)
    {
        val = m.Groups[1].Value;
    }
    return val;
}

注意-代码未经测试,可能需要根据您的需要进行调整。尽管正则表达式已测试。

上面的代码给予你的值从标签在您的情况下执行后的函数的变量将有值

font = "**Italic**"  
datestamp = "2015/02/01 00:00:00"
commentVal = "**this is a My awesome new comments comment.!!**"

然后,如果您希望将其从comment变量中删除,只需使用Replace作为

comment = comment.Replace(font, string.Empty);
comment = comment.Replace(datestamp, string.Empty);
comment = comment.Replace(commentVal, string.Empty);

在它的最后,您将拥有comment变量,其中删除了该标记中的值。

gev0vcfq

gev0vcfq2#

要删除中间的值,可以修改@Coder of Code提供的正则表达式,如下所示:

string str = "[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]";
        string strPattern = @"(?:])([^[]+)\["; // Regular expression pattern to find string inside ][
        Regex rg = new Regex(strPattern);
        string newStr = rg.Replace(str, string.Format("]{0}[",string.Empty), int.MaxValue);

相关问题