【问题标题】:Contains and Regex Returns true but not with exact match包含和正则表达式返回 true 但不完全匹配
【发布时间】:2015-03-12 21:28:55
【问题描述】:

我不知道如何弄清楚这种情况。基本上,我将列表中的信息转换为字符串以使用包含和正则表达式。我需要弄清楚用户是否选择了“其他”选项,如果是,那么做一些事情。但是,在同一个列表中,还有其他以“Other”开头的值可供选择。

示例数据:

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

示例代码:

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

如果用户只选择“Other”,它会正常工作,但是,如果用户没有选择“Other”而是选择“Other Chemical”,则条件仍会返回 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

    }

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

【问题讨论】:

  • 您的 MaterialList 是一个实际的列表还是只是一个特殊格式的字符串?
  • 我感觉MaterialList 只是一个字符串,这个问题是“为什么,如果我问字符串a 包含 字符串b 是否在两个之一中不同的方式,我得到的是我所要求的,而不是指示字符串a 是否完全等于字符串b的结果。"

标签: c# regex contains


【解决方案1】:

谢谢大家。想通了。

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

【讨论】:

    【解决方案2】:

    为什么不使用

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

    或者你生病了do-everything-with-regex

    【讨论】:

    • 您在one-line-method-anything 生病了吗? :P
    • 谢谢。但是当我同时选择“其他”和“其他化学品”时,它返回 false。但如果我只选择“其他”,它会返回 true。
    • @YoryeNathan 好吧,无论如何它都会被编译器内联,因为方法体小于 64 字节
    • @Mus 是的,正如所料,这就是所谓的exact match
    【解决方案3】:

    看起来你可以改用 Linq:

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

    【讨论】:

    • 您假设MaterialList 是一个字符串序列。如果你可以在上面调用ToString并得到一个包含Other的字符串,那似乎不太可能。
    • 嗯,这是一个很好的观点(即使在字符串上调用 ToString() 看起来很奇怪),那么我想你必须引入一些分隔符,否则我不明白你怎么能做到这一点.
    【解决方案4】:

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

    来自 MSDN:

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

    试试这个:

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

    【讨论】:

    • 嗯.. 谢谢。但是当我同时选择“其他”和“其他化学品”时,它返回 false。但如果我只选择“其他”,它会返回 true。
    • 你能从列表中选择两项吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多