【问题标题】:How to detect a particular word in a string using C#?如何使用 C# 检测字符串中的特定单词?
【发布时间】:2015-10-30 01:48:31
【问题描述】:

我需要使用 C# 代码编写一个 if 语句来检测字符串中是否存在单词“any”:

string source ="is there any way to figure this out";

【问题讨论】:

标签: c# if-statement string-matching


【解决方案1】:

请注意,如果您真的想匹配单词(而不是“任何人”之类的东西),您可以使用正则表达式:

string source = "is there any way to figure this out";
string match = @"\bany\b";
bool match = Regex.IsMatch(source, match);

您还可以进行不区分大小写的匹配。

【讨论】:

    【解决方案2】:
    String stringSource = "is there any way to figure this out";
    String valueToCheck = "any";
    
    if (stringSource.Contains(valueToCheck)) {
    
    }
    

    【讨论】:

      【解决方案3】:

      这是一种结合和扩展IllidanS4smoggers的答案的方法:

      public bool IsMatch(string inputSource, string valueToFind, bool matchWordOnly)
      {
          var regexMatch = matchWordOnly ? string.Format(@"\b{0}\b", valueToFind) : valueToFind;
          return System.Text.RegularExpressions.Regex.IsMatch(inputSource, regexMatch);
      }
      

      您现在可以执行以下操作:

      var source = "is there any way to figure this out";
      var value = "any";
      var isWordDetected = IsMatch(source, value, true); //returns true, correct
      

      注意事项:

      • 如果matchWordOnly 设置为true,函数将返回true 对应"any way"false 对应"anyway"
      • 如果matchWordOnly 设置为false,该函数将为"any way""anyway" 返回true。这是合乎逻辑的,因为为了使"any way" 中的“任何”成为一个单词,它首先必须是字符串的一部分。 \B(正则表达式中\b的否定)可以添加到组合中以仅匹配非单词,但根据您的要求,我认为没有必要。

      【讨论】:

      • 如果需要,您还可以使用 Regex.Escape 来防止将正则表达式模式传递给方法。虽然我想不出任何同时也是正则表达式模式的词......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多