替换字符串中的多个范围

时间:2015-01-13 16:14:45

标签: regex vb.net replace

我需要将字符串替换为T9字母。例如:“你好”将成为“32445”

到目前为止,我有以下代码,但每个Regex占用时间,有没有办法在更简单的代码中替换多个范围?

dim tword = word    
tWord = Regex.Replace(tWord, "[abc]","1")
tWord = Regex.Replace(tWord, "[def]","2")
tWord = Regex.Replace(tWord, "[ghi]","3")
tWord = Regex.Replace(tWord, "[jkl]","4")
tWord = Regex.Replace(tWord, "[mno]","5")
tWord = Regex.Replace(tWord, "[pqrs]","6")
tWord = Regex.Replace(tWord, "[tuv]","7")
tWord = Regex.Replace(tWord, "[wxyz]", "8")
RTextBox.Text = RTextBox.Text.Replace(word, tWord)

2 个答案:

答案 0 :(得分:2)

这是一个单行:

Dim result As String = Regex.Replace(word, "[a-z]",
    Function(m) "11122233344455566667778888"(Asc(m.Value) - Asc("a"c)))

使用Regex.Replace overload,其第三个参数为MatchEvaluator,允许您使用任意替换功能 每个Match对象包括一个匹配的字符串(在这种情况下只包含一个匹配的字母)被传递给MatchEvaluator

MatchEvaluator函数内,

  • mMatch个对象,m.Value表示匹配的字符串。
  • Asc(m.Value) - Asc("a"c)将字母表转换为索引0-25。
  • "11122233344455566667778888"(index)正在调用 String.Chars 这是String类的默认属性,即将索引转换为数字。

答案 1 :(得分:1)

您可以将所有字母放在地图中,并在循环输入字符串中的所有字符时快速查找。这样你只需处理一次输入字符串(你的正则表达式方法为每个正则表达式处理字符串一次)。

'This is a one-time setup for the map
Dim map As New Dictionary(Of Char, Char)

map.Add("a"c, "1"c)
map.Add("b"c, "1"c)
map.Add("c"c, "1"c)
map.Add("d"c, "2"c)
'TODO add all other characters that you want to map

'...

Dim buffer As New StringBuilder(word.Length)
Dim chr As Char

For i As Integer = 0 To word.Length - 1
    'If the character appears in the map, use its mapped value
    If map.TryGetValue(word(i), chr) Then
        buffer.Append(chr)
    Else
        'If a character is not found, simply output the input
        'character (modify this behavior as needed)
        buffer.Append(word(i))
    End If
Next i

Dim result = buffer.ToString()