0

试图找出如何用相应的值查找和替换文本。

例如

1) fedex 到 FedEx 2) nasa 到 NASA 3) po box 到 PO BOX

Public Function FindReplace(ByVal s As String) As String

    Dim MatchEval As New MatchEvaluator(AddressOf RegexReplace)

    Dim Pattern As String = "(?<f1>fedex|nasa|po box)"

    Return Regex.Replace(s, Pattern, MatchEval, RegexOptions.IgnoreCase)

End Function

Public Function RegexReplace(ByVal m As Match) As String
    Select Case LCase(m.Groups("f1").Value)
        Case "fedex"
            Return "FedEx"
        Case "nasa"
            Return "NASA"
        Case "po box"
            Return "PO BOX"
    End Select
End Function

上面的代码适用于固定值,但不知道如何使用上面的代码来匹配运行时添加的值,如 db 到 Db。

4

2 回答 2

1

我猜,这里唯一需要 Regex 的就是 IgnoreCase 选项。如果是这样,那么我建议根本不要使用正则表达式。请改用字符串功能:

Dim input As String = "fEDeX"
Dim pattern As String = "fedex"
Dim replacement As String = "FedEx"

Dim result As String

result = input.ToLowerInvariant().Replace(pattern, replacement)

但是,如果您仍然需要正则表达式,那么这应该可以工作:

result = Regex.Replace(input, pattern, replacement, RegexOptions.IgnoreCase)

例子:

Sub Main()
  Dim replacements As New Dictionary(Of String, String)()
  replacements.Add("fedex", "FedEx")
  replacements.Add("nasa", "NASA")
  replacements.Add("po box", "PO BOX")

  Dim result As String = Replace("fedex, nAsA, po box, etc", replacements)
End Sub

Private Function Replace(ByVal input As String, ByVal replacements As Dictionary(Of String, String)) As String
  For Each item In replacements
    input = Regex.Replace(input, item.Key, item.Value, RegexOptions.IgnoreCase)
  Next

  Return input
End Function
于 2013-02-22T11:46:40.953 回答
0

通过使用 List 找到了解决方案,并对 Anton Kedrov 建议的字典对象进行了性能测试,这两种方法都需要几乎相同的时间才能完成,但我不知道字典方法对于更长的替换列表是否好,因为它循环遍历所有列表以查找要替换的匹配条目。

我感谢大家的建议和建议。

Sub Main()
    Dim lst As New List(Of String)

    lst.Add("NASA")
    lst.Add("FedEx")
    lst.Add("PO BOX")

    MsgBox(FindReplace("this is testing fedex naSa PO box"))
End Sub

Public Function FindReplace(ByVal s As String) As String
    Dim Pattern As String = "(?<f1>fedex|nasa|po box)"
    Dim MatchEval As New MatchEvaluator(AddressOf RegexReplace)
    Return Regex.Replace(s, Pattern, MatchEval, RegexOptions.IgnoreCase)

End Function

Public Function RegexReplace(ByVal m As Match) As String
    Dim Found As String
    Found = lst.Find(Function(value As String) LCase(value) = LCase(m.Groups("f1").Value))
    Return Found
End Function
于 2013-02-23T11:42:54.497 回答