2014-08-29 66 views
1

我已經實現了答案在這裏做一個字符串替換令牌替換:現在 https://stackoverflow.com/a/1231815/1224021字符串字典異常處理

我的問題是,當這種方法找到了一個令牌,是不是在字典中的值。我得到了例外:「給定的密鑰不在字典中。」並返回正常的字符串。我想要發生的事情顯然是所有的好令牌都被取代了,但是違規的令牌仍然是自動的。猜測我需要做一個循環與一行正則表達式替換?使用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 
+0

那一行是拋出的異常? – djv 2014-08-29 15:16:32

回答

1

這是我得到了什麼工作對正則表達式,這也是原來的線程上建議由Allen Wanghttps://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 
1

異常被拋出可能在該行

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

,因爲這是你的密鑰字典中的唯一的地方。在訪問它之前使用Dictionary.ContainsKey method

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

我認爲這工作,但現在看到它弄亂了我的HTML字符串。它在遇到缺失的字典條目時重複或替換錯誤的部分。儘管感謝您讓我知道ContainsKey。 – 2014-08-29 16:26:05

0

我知道它已經有一段時間,因爲這個問題,得到的回答,但FYI想要的任何人仍然使用正則表達式/詞典匹配的方式,以下作品(基於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)正則表達式是個懶惰初始化和編譯,以適應我的具體使用情況:

  • 屏幕此代碼投放可能不會經常使用
  • 但一旦它,它會得到大量使用
  • 所以應該在後續調用盡可能高效。