替换字符串中的多个范围

Replace many ranges in a string

我需要将一个字符串替换成T9字母。例如:"hello" 将变为“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)

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

'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()

这是单行代码:

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

使用 Regex.Replace overload whose third parameter is MatchEvaluator 允许您任意替换的功能。
每个包含匹配字符串的 Match 对象(在本例中只包含一个匹配的字母)被传递给 MatchEvaluator

MatchEvaluator 函数中,

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