如何检查字符串是否与 Scala 中的正则表达式完全匹配? [英] How to check whether a String fully matches a Regex in Scala?
问题描述
假设我有一个正则表达式模式,我想将许多字符串与之匹配.
Assume I have a Regex pattern I want to match many Strings to.
val Digit = """\d""".r
我只想检查给定的字符串是否与正则表达式完全匹配.在 Scala 中执行此操作的好方法是什么?
I just want to check whether a given String fully matches the Regex. What is a good and idiomatic way to do this in Scala?
我知道我可以在正则表达式上进行模式匹配,但是在这种情况下这在语法上不是很令人满意,因为我没有要提取的组:
I know that I can pattern match on Regexes, but this is syntactically not very pleasing in this case, because I have no groups to extract:
scala> "5" match { case Digit() => true case _ => false }
res4: Boolean = true
或者我可以回到底层的 Java 模式:
Or I could fall back to the underlying Java pattern:
scala> Digit.pattern.matcher("5").matches
res6: Boolean = true
这也不优雅.
有更好的解决方案吗?
推荐答案
回答我自己的问题我将使用pimp my library pattern"
Answering my own question I'll use the "pimp my library pattern"
object RegexUtils {
implicit class RichRegex(val underlying: Regex) extends AnyVal {
def matches(s: String) = underlying.pattern.matcher(s).matches
}
}
并像这样使用它
import RegexUtils._
val Digit = """\d""".r
if (Digit matches "5") println("match")
else println("no match")
除非有人想出更好的(标准)解决方案.
unless someone comes up with a better (standard) solution.
注意事项
我没有拉皮条
String
来限制潜在副作用的范围.
I didn't pimp
String
to limit the scope of potential side effects.
unapplySeq
在这种情况下读起来不太好.
unapplySeq
does not read very well in that context.
这篇关于如何检查字符串是否与 Scala 中的正则表达式完全匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!