使用转义符号获取正则表达式

时间:2014-03-26 14:31:33

标签: c# regex

我非常感谢非工作正则表达式的帮助(不适用于特殊符号%或$)

    public System.Tuple<string, string> GetParts(string str, string beginMark, string endMark)
    {
        var pattern =
            new Regex(beginMark + @"(?<val>.*?)" + endMark,
                RegexOptions.Compiled |
                RegexOptions.Singleline);

        return (from Match match in pattern.Matches(str)
                where match.Success
                select new Tuple(
                    match.Value,
                    match.Groups["val"].Value))
               .ToList();
    } 

通话方式:

string input = @"%sometext%\another text";
string replacedValue = "AAA";
var occurrences = GetPart(input, @"(%", ")");
foreach (var occurrence in occurrences)
{
    Console.WriteLine(occurrence.Item1 + Environment.NewLine);
    Console.WriteLine(occurrence.Item2 + Environment.NewLine);
    // replace
    onsole.WriteLine(input.Replace(occurrence.Item1, replacedValue) + Environment.NewLine);
}

预期产出:

%sometext%

sometext

AAA \另一个文字

1 个答案:

答案 0 :(得分:1)

你需要逃避你的符号。尝试改变

new Regex(beginMark + @"(?<val>.*?)" + endMark,

new Regex(Regex.Escape(beginMark) + @"(?<val>.*?)" + Regex.Escape(endMark),