[英]C# \b not being found
Match m = Regex.Match(richText, "\\\\par\b", RegexOptions.None);
richText = Regex.Replace(richText, "\\\\par\b", "", RegexOptions.IgnoreCase);
Input:输入:
"{\\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}"
I'd like it to find the \\par only, and not the \\pard that can be found in the middle of the input.我希望它只找到 \\par ,而不是可以在输入中间找到的 \\pard 。
Backslashes are escape characters in both string literals and regexes, so when you have a regex in a string literal you need to either double the backslashes or prefix the string literal with @
.反斜杠在字符串文字和正则表达式中都是转义字符,因此当您在字符串文字中有正则表达式时,您需要将反斜杠加倍或在字符串文字前加上@
。
You're not doubling for the \b
, so it's a backspace character.你没有为\b
加倍,所以它是一个退格字符。
[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"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.