我经常将字符串与正则表达式匹配。在Java中:
java.util.regex.Pattern.compile("\w+").matcher("this_is").matches
唉哟。Scala有很多选择。
"\\w+".r.pattern.matcher("this_is").matches"this_is".matches("\\w+")"\\w+".r unapplySeq "this_is" isDefinedval R = "\\w+".r; "this_is" match { case R() => true; case _ => false}第一种方法和Java代码一样重。
第二个问题是无法提供编译模式("this_is".matches("\\w+".r"))。(这似乎是一种反模式,因为几乎每次有一个方法需要regex编译,就有一个重载需要regex)。
第三个问题是它滥用了unapplySeq,因此很神秘。
第四种方法在分解正则表达式的部分时很好,但是当你只想要一个布尔结果时,它太重了。
我是不是遗漏了一种检查正则表达式匹配的简单方法?为什么没有定义String#matches(regex: Regex): Boolean?实际上,String#matches(uncompiled: String): Boolean是在哪里定义的?
发布于 2011-11-28 21:04:21
您可以定义如下模式:
scala> val Email = """(\w+)@([\w\.]+)""".r如果匹配,findFirstIn将返回Some[String],否则将返回None。
scala> Email.findFirstIn("test@example.com")
res1: Option[String] = Some(test@example.com)
scala> Email.findFirstIn("test")
rest2: Option[String] = None你甚至可以提取:
scala> val Email(name, domain) = "test@example.com"
name: String = test
domain: String = example.com最后,您还可以使用常规的String.matches方法(甚至回收先前定义的Email Regexp:
scala> "david@example.com".matches(Email.toString)
res6: Boolean = true希望这能帮上忙。
https://stackoverflow.com/questions/8301858
复制相似问题