在 Scala 中匹配正则表达式 [英] Matching against a regular expression in Scala

查看:48
本文介绍了在 Scala 中匹配正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常将字符串与正则表达式进行匹配.在 Java 中:

I fairly frequently match strings against regular expressions. In Java:

java.util.regex.Pattern.compile("\w+").matcher("this_is").matches

java.util.regex.Pattern.compile("\w+").matcher("this_is").matches

哎哟.Scala 有很多选择.

Ouch. Scala has many alternatives.

  1. "\\w+".r.pattern.matcher("this_is").matches
  2. "this_is".matches("\\w+")
  3. "\\w+".r unapplySeq "this_is" isDefined
  4. val R = "\\w+".r;this_is"匹配{ case R() =>真的;案例_ =>false}

第一个和 Java 代码一样重量级.

The first is just as heavy-weight as the Java code.

第二个的问题是你不能提供一个编译模式 ("this_is".matches("\\w+".r")).(这似乎是一个反-pattern 因为几乎每次有一个使用正则表达式编译的方法时,都会有一个使用正则表达式的重载).

The problem with the second is that you can't supply a compiled pattern ("this_is".matches("\\w+".r")). (This seems to be an anti-pattern since almost every time there is a method that takes a regex to compile there is an overload that takes a regex).

第三个的问题在于它滥用了unapplySeq,因此很神秘.

The problem with the third is that it abuses unapplySeq and thus is cryptic.

第四个在分解正则表达式的部分时很好,但当你只想要一个布尔结果时就太重了.

The fourth is great when decomposing parts of a regular expression, but is too heavy-weight when you only want a boolean result.

我是否缺少一种检查正则表达式匹配项的简单方法?String#matches(regex: Regex): Boolean 是否有定义?其实String#matches(uncompiled: String): Boolean是在哪里定义的?

Am I missing an easy way to check for matches against a regular expression? Is there a reason why String#matches(regex: Regex): Boolean is not defined? In fact, where is String#matches(uncompiled: String): Boolean defined?

推荐答案

你可以这样定义模式:

scala> val Email = """(\w+)@([\w\.]+)""".r

findFirstIn 将返回 Some[String] 如果匹配,否则返回 None.

findFirstIn will return Some[String] if it matches or else 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:

Finally, you can also use conventional String.matches method (and even recycle the previously defined Email Regexp :

scala> "david@example.com".matches(Email.toString)
res6: Boolean = true

希望这会有所帮助.

这篇关于在 Scala 中匹配正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆