我经常将字符串与正则表达式匹配。在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希望这能帮上忙。
发布于 2011-11-28 21:17:32
我为这个问题创建了一个小小的“拉皮条我的图书馆”模式。也许它能帮到你。
import util.matching.Regex
object RegexUtils {
class RichRegex(self: Regex) {
def =~(s: String) = self.pattern.matcher(s).matches
}
implicit def regexToRichRegex(r: Regex) = new RichRegex(r)
}使用实例
scala> import RegexUtils._
scala> """\w+""".r =~ "foo"
res12: Boolean = true发布于 2015-03-19 13:50:31
我通常用
val regex = "...".r
if (regex.findFirstIn(text).isDefined) ...但我觉得这很尴尬。
https://stackoverflow.com/questions/8301858
复制相似问题