【问题标题】:replace text in a string with .net regexp用 .net 正则表达式替换字符串中的文本
【发布时间】:2010-10-10 23:53:10
【问题描述】:

我尝试在 .net 中使用正则表达式来查找和替换带有特定标记的字符串,例如

myString = "这是我要更改的文本示例 和 "

我如何找到带有“”之间标记的文本,并为每个标记做一些事情来替换它(在数据库中搜索并替换任何找到的匹配项)?

我想要的结果:

myString = "这是我想要更改 someValueFromDb 和 anotherValueFromDb 的文本示例"

谢谢。

【问题讨论】:

    标签: c# .net regex string


    【解决方案1】:

    下面是一个使用Regex.Replace 的示例,它使用MatchEvaluator 通过在字典中检查指定令牌来执行替换。如果字典中不存在令牌,则文本保持不变。

    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    
    namespace TokenReplacement
    {
        class Program
        {
            static void Main(string[] args)
            {
                string text = "this is a example of my text that I want to change <#somevalue#> and <#anothervalue#>";
    
                var tokens = new Dictionary<string, string>
                {
                    { "somevalue", "Foo" },
                    { "anothervalue", "Bar" }
                };
    
                Console.WriteLine(Replace(text, tokens));
            }
    
            static string Replace(string input, Dictionary<string, string> tokens)
            {
                MatchEvaluator evaluator = match =>
                {
                    string token;
                    if (tokens.TryGetValue(match.Groups[1].Value, out token))
                        return token;
    
                    return match.Value;
                };
    
                return Regex.Replace(input, "<#(.*?)#>", evaluator);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      解决方案 1

      这里有一个相当彻底的基于正则表达式的令牌替换和文档:

      http://www.simple-talk.com/dotnet/asp.net/regular-expression-based-token-replacement-in-asp.net/

      解决方案 2

      如果您不想添加那么多代码,这里有另一种方法。此代码在配置文件 AppSettings 部分中查找令牌(格式类似于 #MyName#)我在另一个项目中使用了类似的方法在资源和数据库中查找它们(或在特定优先级中查找所有 3 个)。如果您愿意,可以通过更改正则表达式和字符串替换行来更改标记的格式。

      当然,这仍然可以通过在整个过程中使用正则表达式来调整以获得更好的性能。

      Public Shared Function ProcessConfigurationTokens(ByVal Source As String) As String
          Dim page As Page = CType(Context.Handler, Page)
          Dim tokens() As String = GetConfigurationTokens(Source)
          Dim configurationName As String = ""
          Dim configurationValue As String = ""
      
          For Each token As String In tokens
              'Strip off the # signs
              configurationName = token.Replace("#"c, "")
      
              'Lookup the value in the configuration (if any)
              configurationValue = ConfigurationManager.AppSettings(configurationName)
      
              If configurationValue.Contains(".aspx") OrElse configurationValue.Contains("/") Then
                  Try
                      Source = Source.Replace(token, page.ResolveUrl(configurationValue))
                  Catch
                      Source = Source.Replace(token, configurationValue)
                  End Try
              Else
                  'This is an optimization - if the content doesn't contain
                  'a forward slash we know it is not a url.
                  Source = Source.Replace(token, configurationValue)
              End If
          Next
      
          Return Source
      End Function
      
      Private Shared Function GetConfigurationTokens(ByVal Source As String) As String()
          'Locate any words in the source that are surrounded by # symbols
          'and return the list as an array.
          Dim sc As New System.Collections.Specialized.StringCollection
      
          Dim r As Regex
          Dim m As Match
      
          If Not String.IsNullOrEmpty(Source) Then
      
              r = New Regex("#[^#\s]+#", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
              m = r.Match(Source)
              While m.Success
      
                  sc.Add(m.Groups(0).Value)
      
                  m = m.NextMatch
              End While
      
              If Not sc.Count = 0 Then
                  Dim result(sc.Count - 1) As String
                  sc.CopyTo(result, 0)
      
                  Return result
              End If
          End If
      
          Return New String() {}
      
      End Function
      

      【讨论】:

        【解决方案3】:

        您想使用接受 MatchEvaluator 委托的 Regex.Replace 方法。此委托将允许您动态提供替换文本。

        Regex.Replace(yourString, @"\<\#([^#]+)\#\>", delegate(Match match)
            {
               // Your code here - use match.ToString()
               // to get the matched string
            });
        

        【讨论】:

        • 我使用了 Regex.Replace(text, "<:>", delegate(Match match) {return match.ToString() + "test"; });但它并没有改变文本,我怎么能用这个代表做到这一点?谢谢
        • 正是我想要的!我知道有办法做到这一点。谢谢。
        【解决方案4】:

        感谢所有回复,我在Replace tokens in an aspx page on load 上找到了答案,这正是我所需要的

        感谢为我指明正确方向的链接和示例。

        private string ParseTagsFromPage(string pageContent)
            {
                string regexPattern = "{zeus:(.*?)}"; //matches {zeus:anytagname}
                string tagName = "";
                string fieldName = "";
                string replacement = "";
                MatchCollection tagMatches = Regex.Matches(pageContent, regexPattern);
                foreach (Match match in tagMatches)
                {
                    tagName = match.ToString();
                    fieldName = tagName.Replace("{zeus:", "").Replace("}", "");
                    //get data based on my found field name, using some other function call
                    replacement = GetFieldValue(fieldName); 
                    pageContent = pageContent.Replace(tagName, replacement);
                }
                return pageContent;
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-13
          • 2015-11-30
          • 2021-11-29
          • 2017-02-04
          相关资源
          最近更新 更多