【问题标题】:Using Regex.Replace() to replace text in a string使用 Regex.Replace() 替换字符串中的文本
【发布时间】:2010-05-27 01:14:44
【问题描述】:

我想使用 Regex.Replace() 循环遍历包含由“//”分隔的单词的字符串,以检查是否有任何单词与已传递给该方法的字符串值匹配。如果文本字符串确实匹配 wordList 中的单词之一,则替换它并返回“匹配”,如果它不匹配任何单词,则返回传递给方法的原始单词并且不替换它。

这是我目前的代码:

    public void CheckText(string text)
    {
        //Check text entered by user

        string wordList = "word1//word2//word3 etc...";
        string replaceString = "matched";

        if (!string.IsNullOrEmpty(wordList))
        {
            //How do I implement this part?
            return Regex.Replace(text, wordList, replaceString); 
        }
    }

请有人帮我解决这个问题吗?任何帮助/cmets 将不胜感激!

更新:(从更新粘贴到 OP 作为答案发布的问题)

感谢您的回复。我可能没有正确解释这个问题。如果它与 wordList 中的字符串匹配,我希望该方法替换它传递的文本字符串。例如,'word1' 被传递给方法,然后方法检查 'word1' 是否在 wordList 中,如果是,则将传递给方法的原始字符串替换为 'matched',然后返回 ' matched',如果不匹配 wordList 中的任何单词,则返回原始字符串,不要替换它。

【问题讨论】:

  • 不清楚你想返回什么(如果你的方法有什么)。 void 表示您不想返回任何内容,方法名称 CheckText 建议您要返回 Boolean 值,return line 表示您要返回 string 值(来自Regex.Replace)。也许澄清你想要达到的目标,我们可以更好地帮助你。

标签: c#


【解决方案1】:

您不需要正则表达式 - String.Replace 可以正常工作 - 它也更具可读性:

public void CheckText(string text)
{
    string wordList = "word1//word2//word3 etc...";
    string replaceString = "matched";

    return wordList.Replace(text, replaceString ); 
}

更新:(更新问题后)

如果您只是想检查传入的字符串是否存在于单词列表中,您可以简单地使用String.IndexOf(如果不存在则返回-1)。但是,您还没有为函数指定返回类型,所以我不知道您希望如何报告结果:

public string CheckText(string text)
{
    string wordList = "word1//word2//word3 etc...";
    if(wordList.IndexOf(text) > -1)
      return "matched";

    return text; 
}

如果传入的文本参数包含在wordList中,上述函数将返回“匹配”,否则返回文本参数本身。

【讨论】:

    【解决方案2】:

    如果你的意思是这些词中的任何一个都应该匹配,那么你需要一个像这样的正则表达式

    new Regex("(word1)|(word2)|(word3)");
    

    所以你必须将你的单词列表转换成这样的正则表达式:

    string wordList = "word1//word2//word3";
    // search every word that ends with '//' or with the end of the string
    // then replace it by (word)|
    // trim the last '|'
    string transformed = Regex.Replace(wordList, @"(\w{1,})(//|$)", "($1)|").TrimEnd('|');
    
    // transformed contains (word1)|(word2)|(word3) now
    

    现在使用transformed 作为您的正则表达式。

    return Regex.Replace(text, transformed, replaceString); 
    

    回应评论使用

    string result = new Regex(transformed).Match(text).Success ? replaceString : "";
    

    如果不匹配则返回空字符串,否则返回replaceString中的内容。

    【讨论】:

    • 感谢您的回复和代码示例,我认为这就是我希望代码执行的操作。基本上,如果传递给方法的单词与 wordList 中的任何单词匹配,我想用“matched”替换它,然后如果它与 wordList 中的一个单词匹配,则返回“matched”,如果它不匹配'不匹配其中任何一个返回原始文本字符串并且不替换它。
    【解决方案3】:

    如果您只想替换字符串,您可能需要使用String.Replace。也许如果您包含给定输入的预期结果,我们也许可以更好地帮助您。

    【讨论】:

      【解决方案4】:

      如果你真的想通过正则表达式来做,那么你可以将它用作字符串的扩展方法:

      private static Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
      public static string RegexReplace(this string value, string pattern, string replacement)
      {
          return RegexReplaceInternal(value, pattern, replacement, RegexOptions.Compiled);
      }
      
      private static object rriLocker = new object();
      private static string RegexReplaceInternal(string value, string pattern, string replacement, RegexOptions regexOptions)
      {
          bool isInCache;
          lock (rriLocker)
          {
              isInCache = regexCache.ContainsKey(pattern);
          }
          if (isInCache)
          {
              return regexCache[pattern].Replace(value, replacement);
          }
          lock (rriLocker)
          {
              Regex rx = new Regex(pattern, RegexOptions.Compiled);
              regexCache.Add(pattern, rx);
              return rx.Replace(value, replacement);
          }
      }
      

      然后:

      var expression = string.Concat("(", wordList.Replace("//", "|"), ")");
      var output = text.RegexReplace(expression, replaceString);
      

      :)

      【讨论】:

      • 不错的帖子对未来有帮助
      猜你喜欢
      • 2013-02-05
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      相关资源
      最近更新 更多