【问题标题】:regex - match everything except certain strings正则表达式 - 匹配除某些字符串之外的所有内容
【发布时间】:2012-09-05 23:34:02
【问题描述】:

为了验证正则表达式,我使用了 Scala 控制台: "REGEX".r.findFirstIn("exampleString").isDefinied

我有很多字符串,我想用正则表达式匹配。
每当字符串恰好是“foo”或“bar”时,我希望上面的内容为假。

我得到的最接近的是^((?!foo|bar).)*$。
但是,问题在于,一旦包含“foo”或“bar”,一切都是假的,尽管我希望“foof”为真。

更新:
我确实需要这个正则表达式来配​​置脚本。所以我不能使用 Scala 方法或改变正则表达式的处理方式。

【问题讨论】:

    标签: regex scala


    【解决方案1】:

    为什么不只允许那些不匹配^(foo|bar)$的字符串?如果这不是一个选项,试试这个正则表达式:^(?!^(foo|bar)$).*$。

    【讨论】:

    • 谢谢,但我无法更改行为,因为这只是现有脚本的配置
    • 我添加了另一个正则表达式来回答。
    【解决方案2】:

    这个怎么样?

    scala> def isFooOrBar(s: String) = !s.matches("""foo|bar""")
    isFooOrBar: (s: String)Boolean
    
    scala> isFooOrBar("foo")
    res4: Boolean = false
    
    scala> isFooOrBar("bar")
    res5: Boolean = false
    
    scala> isFooOrBar("foof")
    res6: Boolean = true
    

    【讨论】:

    • def isFooOrBar(s: String) = !s.matches("""foo|bar""") 应该够了
    • @sschaef,好电话。已更新。
    • 谢谢你们,但我无法更改脚本。我需要正则表达式来配​​置脚本。
    【解决方案3】:

    此模式适用于^(?!(foo|bar)$)。一个测试示例:

    import java.util.regex.Pattern;
    
    object NotRE extends App {
      val p = Pattern.compile("^(?!(foo|bar)$)");
    
      val test = Seq("foo", "bar", "1foo", "foo1", "2bar", "bar2", "3bar3", "3foo3");
    
      print(test map ((x: String) => (x, p.matcher(x).find())));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多