Regex.Replace正在剥离管道角色

时间:2014-03-18 12:20:29

标签: .net regex

我有这个功能,它应该像á,ä等交换每个空间字符,用于像 a 这样的普通字符:

Private Function QuitaTildes(ByVal texto As String) As String
    Dim replace_a As Regex,
        replace_e As Regex,
        replace_i As Regex,
        replace_o As Regex,
        replace_u As Regex

    replace_a = New Regex("[á|à|ä|â]", RegexOptions.Compiled)
    replace_e = New Regex("[é|è|ë|ê]", RegexOptions.Compiled)
    replace_i = New Regex("[í|ì|ï|î]", RegexOptions.Compiled)
    replace_o = New Regex("[ó|ò|ö|ô]", RegexOptions.Compiled)
    replace_u = New Regex("[ú|ù|ü|û]", RegexOptions.Compiled)

    texto = replace_a.Replace(texto, "a")
    texto = replace_e.Replace(texto, "e")
    texto = replace_i.Replace(texto, "i")
    texto = replace_o.Replace(texto, "o")
    texto = replace_u.Replace(texto, "u")

    Return texto
End Function

问题是,当texto是一个正则表达式模式本身,如"one|twó|threé"时,它返回"onetwothree",这就是,它取出了每个|字符,为什么?这个文本在替换字符串中,而不是在模式中,所以我不需要逃避它。

是否有正则表达式的选项告诉它停止这样做?

(这个功能是为了节省一些加压时间,所以如果我需要转义| char,我就不会保存那么多)

谢谢

2 个答案:

答案 0 :(得分:3)

你不需要|符号

replace_a = New Regex("[áàäâ]", RegexOptions.Compiled)
replace_e = New Regex("[éèëê]", RegexOptions.Compiled)
replace_i = New Regex("[íìïî]", RegexOptions.Compiled)
replace_o = New Regex("[óòöô]", RegexOptions.Compiled)
replace_u = New Regex("[úùüû]", RegexOptions.Compiled)

答案 1 :(得分:1)

您的模式中的[]或模式中的|

|用于OR,但通常用于your|you're,可用于群组()。方括号也是OR,但对于其中的任何一个字符。