C#  not being found

本文关键字:found being not | 更新日期: 2023-09-27 18:03:08

        Match m = Regex.Match(richText, "''''par'b", RegexOptions.None);
        richText = Regex.Replace(richText, "''''par'b", "", RegexOptions.IgnoreCase);
输入:

"{''rtf1''ansi''ansicpg1252''deff0''deflang1033{''fonttbl{''f0''fnil Arial;}{''f1''fnil''fcharset0 Microsoft Sans Serif;}}''viewkind4''uc1''pard''f0''fs20 CC: not specified''f1''fs17''par}"

我希望它只找到''par,而不是在输入中间可以找到的''pard。

C#  not being found

反斜杠在字符串字面值和正则表达式中都是转义字符,所以当你在字符串字面值中有一个正则表达式时,你需要将反斜杠加倍或在字符串字面值前加上@

你没有为'b加两倍,所以它是一个退格字符。

MRAB正确:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestWithDoubleBackslash()
    {
        const string regex1 = "''''par''b";
        TestRegEx(regex1);
    }
    [TestMethod]
    public void TestWithSingleBackslash()
    {
        const string regex2 = "''''par'b";
        TestRegEx(regex2);
    }
    private static void TestRegEx(string regex)
    {
        var richText =
            "{''rtf1''ansi''ansicpg1252''deff0''deflang1033{''fonttbl{''f0''fnil Arial;}{''f1''fnil''fcharset0 Microsoft Sans Serif;}}''viewkind4''uc1''pard''f0''fs20 CC: not specified''f1''fs17''par}";
        Match m = Regex.Match(richText, regex, RegexOptions.None);
        var output = Regex.Replace(richText, regex, "", RegexOptions.IgnoreCase);
        Console.WriteLine("BEFORE : [" + richText + "]");
        Console.WriteLine("AFTER  : [" + output + "]");
        Assert.IsTrue(output.Contains("pard"));
        Assert.IsFalse(output.Contains("fs17''par"));
    }
}