替换包含花括号的字符串

时间:2017-03-14 13:03:36

标签: c# .net regex asp.net-mvc powershell

我有一个像

这样的声明
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

我想将"The {0} must be at least {2} characters long."替换为"TestString"。 目前我正在使用Regex.Replace,但它不起作用。 e.g。

string lno = "[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]";
pattern = "The {0} must be at least {2} characters long.";
string _name = Regex.Replace(lno, pattern, "TestString", RegexOptions.None);

请帮助。

修改 我正在解析一个类的每一行(使用visual studio shell包),并在找到时尝试替换提到的字符串。我将行号值存储到" lno"。这就是为什么我在这里初始化它的原因。 它适用于普通条纹,如:

[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

只有在用大括号解析字符串时才会出现问题。

谢谢。

3 个答案:

答案 0 :(得分:2)

没有必要将Regex用于您想要完成的任务......

string lno = "[StringLength(100, ErrorMessage = \"The {0} must be at least {2} characters long.\", MinimumLength = 6)]";
string pattern = "The {0} must be at least {2} characters long.";
string _name = lno.Replace(pattern, "TestString");

答案 1 :(得分:2)

您可以使用Regex.Escape方法转义字符串:

string lno = "[StringLength(100, ErrorMessage = \"The {0} must be at least {2} characters long.\", MinimumLength = 6)]";
string pattern = Regex.Escape("The {0} must be at least {2} characters long.");
string _name = Regex.Replace(lno, pattern, "TestString", RegexOptions.None);

来自MSDN:

  

通过将其替换为转义码来转义一组最小字符(\,*,+,?,|,{,[,(,),^,$ ,.,#和空格)。这指示正则表达式引擎按字面解释这些字符而不是元字符。

答案 2 :(得分:1)

定义正则表达式时必须小心。 {}.等字符,只是在表达式中列出一些内容,具有特殊含义,需要进行转义。

var lno = "[StringLength(100, ErrorMessage = \"The {0} must be at least {2} characters long.\", MinimumLength = 6)]";
var pattern = @"The \{0\} must be at least \{2\} characters long\."; // Don't forget the @
string _name = Regex.Replace(lno, pattern, "TestString", RegexOptions.None);

FIDDLE https://dotnetfiddle.net/var2Fj