字符串替换为字典异常处理



我在这里实现了对字符串进行标记替换的答案:https://stackoverflow.com/a/1231815/1224021

我现在的问题是,当这个方法找到一个值不在字典中的令牌时。我得到一个异常"给定的键不在字典中",然后只返回正常的字符串。很明显,我希望所有好的代币都被替换掉,但冒犯的代币仍然是自然的。猜测我需要做一个循环与单行regex替换?使用vb.net。以下是我目前正在做的:

Shared ReadOnly re As New Regex("$(w+)$", RegexOptions.Compiled)
Public Shared Function GetTokenContent(ByVal val As String) As String
    Dim retval As String = val
    Try
        If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then
            Dim args = GetRatesDictionary()
            retval = re.Replace(val, Function(match) args(match.Groups(1).Value))
        End If
    Catch ex As Exception
        ' not sure how to handle?
    End Try
    Return retval
End Function

异常可能在行中抛出

retval = re.Replace(val, Function(match) args(match.Groups(1).Value))

因为这是你在字典里唯一的地方。访问Dictionary.ContainsKey方法之前,请先使用该方法。

retval = re.Replace(val, 
             Function(match)
                 return If(args.ContainsKey(match.Groups(1).Value), args(match.Groups(1).Value), val)
             End Function)

这是我与regex的对比,regex也是Allen Wang对原始线程的建议:https://stackoverflow.com/a/7957728/1224021

Public Shared Function GetTokenContent(ByVal val As String) As String
    Dim retval As String = val
    Try
        If Not String.IsNullOrEmpty(val) AndAlso val.Contains("$") Then
            Dim args = GetRatesDictionary("$")
            retval = args.Aggregate(val, Function(current, value) current.Replace(value.Key, value.Value))
        End If
    Catch ex As Exception
    End Try
    Return retval
End Function

我知道这个问题已经有一段时间没有得到回答了,但仅供所有想仍然使用Regex/Dictionary匹配方法的人参考,以下方法有效(基于OP问题中的示例):

retVal = re.Replace(formatString,
                    match => args.ContainsKey(match.Groups[1].Captures[0].Value)
                        ? args[match.Groups[1].Captures[0].Value]
                        : string.Empty);

或者我的完整样本作为字符串扩展方法是:

 public static class StringExtensions
        {
// Will replace parameters enclosed in double curly braces
            private static readonly Lazy<Regex> ParameterReplaceRegex = new Lazy<Regex>(() => new Regex(@"{{(?<key>w+)}}", RegexOptions.Compiled));
            public static string InsertParametersIntoFormatString(this string formatString, string parametersJsonArray)
            {
                if (parametersJsonArray != null)
                {
                    var deserialisedParamsDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(parametersJsonArray);
                    formatString = ParameterReplaceRegex.Value.Replace(formatString,
                        match => deserialisedParamsDictionary.ContainsKey(match.Groups[1].Captures[0].Value)
                            ? deserialisedParamsDictionary[match.Groups[1].Captures[0].Value]
                            : string.Empty);
                }
                return formatString;
            }
        }

这里有几点需要注意:1) 我的参数以JSON数组的形式传入,例如:{"ProjectCode":"12345","AnotherParam":"Hi there!"}2) 要进行替换的实际模板/格式字符串的参数用双大括号括起来:"This is the Project Code: {{ProjectCode}}, this is another param {{AnotherParam}}"3) Regex是Lazy初始化和编译的,以适应我的特定用例:

  • 该代码所服务的屏幕可能不会经常使用
  • 但一旦成功,它就会得到大量使用
  • 因此它应该在后续调用中尽可能高效

最新更新