代码之家  ›  专栏  ›  技术社区  ›  Lost_In_Library

regex.ismatch返回true,这不正确

  •  0
  • Lost_In_Library  · 技术社区  · 8 年前

    我有一个这样的扩展方法;

    public static bool IsBoolean(this string value)
    {
        string lower = value.ToLower(CultureInfo.InvariantCulture);
        return new Regex("[true]|[false]|[0]|[1]", RegexOptions.Compiled).IsMatch(lower);
    }
    

    但当我给出“fals”或“tru”作为值时,这个regex模式失败了。例如:

    [Theory(DisplayName = "IsBoolean")]
    [InlineData("FALS")]
    [InlineData("Fals")]
    [InlineData("TRU")]
    [InlineData("Tru")]
    public void IsNotBoolean(string value)
    {
        bool result = value.IsBoolean();
        Assert.False(result);
    }
    

    所有这些测试都失败了。因为结果是真的。
    这怎么可能?这个regex模式错误吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   Sweeper    8 年前

    您需要检查字符串是否为以下任何一个字符串,忽略大小写,

    true
    false
    1
    0
    

    然后你就用 | 用它作为正则表达式,并使用 IgnoreCase 选项:

    public static bool IsBoolean(this string value) {
        // note the ^ and $. They assert the start and end of the string.
        return new Regex("^(?:true|false|0|1)$", RegexOptions.IgnoreCase).IsMatch(value);
    }
    

    [] 表示一个字符类,因此它将匹配其中的任何一个字符。 [abc] 比赛 任何一个 a , b c . 注意区别。