包含和正则表达式返回 true,但不完全匹配

本文关键字:不完全 true 正则表达式 返回 包含 | 更新日期: 2023-09-27 18:37:27

我对如何弄清楚这种情况感到困惑。 基本上,我将列表中的信息转换为字符串以使用包含和正则表达式。 我需要弄清楚用户是否选择了"其他"选项,如果是,那就做点什么。 但是,在同一列表中,还有其他值可供选择,这些值也以"其他"开头。

示例数据:

  • 防火材料
  • 其他
  • 其他化学品

示例代码:

if(MaterialList.ToString().Contains("Other"))
    {   
"Do This If Other Is Selected";
    }
else
    {
"Do That If Other Isn't Selected";
    }
如果用户只选择"其他",则

工作正常,但是,如果用户不选择"其他"而是选择"其他化学品",则条件仍返回 true。

我也尝试了以下方法,它的行为相同:

public static bool ExactMatch(string input, string match)
    {
    return Regex.IsMatch(input, string.Format(@"{0}", Regex.Escape(match)));
    //actually doesn't find the exact match - just a portion of the string
    }

可能不应使用"包含"或"匹配",但不确定如何解决问题。

包含和正则表达式返回 true,但不完全匹配

看起来你可以改用 Linq:

if (MaterialList.Any(m => m == "Other"))
    ...

您可以在您的情况下使用String.EndsWith()函数

从 MSDN:

确定此字符串实例的末尾是否与 指定的字符串。

试试这个:

if(MaterialList.ToString().EndsWith("Other"))
{   
   "Do This If Other Is Selected";
}
else
{
   "Do That If Other Isn't Selected";
}

为什么不使用

public static bool ExactMatch(string input, string match)
{
    return input == match;
}

还是你生病了do-everything-with-regex

谢谢大家。 想通了。

if(MaterialsList.ToString().Split(''t').Contains("Other"))