How to check whether a String fully matches a Regex in Scala?

后端 未结 6 407
长发绾君心
长发绾君心 2020-12-23 11:14

Assume I have a Regex pattern I want to match many Strings to.

val Digit = \"\"\"\\d\"\"\".r

I just want to check whether a given String fu

相关标签:
6条回答
  • 2020-12-23 11:27

    For the full match you may use unapplySeq. This method tries to match target (whole match) and returns the matches.

    scala> val Digit = """\d""".r
    Digit: scala.util.matching.Regex = \d
    
    scala> Digit unapplySeq "1"
    res9: Option[List[String]] = Some(List())
    
    scala> Digit unapplySeq "123"
    res10: Option[List[String]] = None
    
    scala> Digit unapplySeq "string"
    res11: Option[List[String]] = None
    
    0 讨论(0)
  • 2020-12-23 11:37

    I don't know Scala all that well, but it looks like you can just do:

    "5".matches("\\d")
    

    References

    • http://langref.org/scala/pattern-matching/matching
    0 讨论(0)
  • 2020-12-23 11:38
      """\d""".r.unapplySeq("5").isDefined            //> res1: Boolean = true
      """\d""".r.unapplySeq("a").isDefined            //> res2: Boolean = false
    
    0 讨论(0)
  • 2020-12-23 11:44

    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
      }
    }
    

    and use it like this

    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.

    Notes

    • I didn't pimp String to limit the scope of potential side effects.

    • unapplySeq does not read very well in that context.

    0 讨论(0)
  • 2020-12-23 11:47

    Using Standard Scala library and a pre-compiled regex pattern and pattern matching (which is scala state of the art):

    val digit = """(\d)""".r
    
    "2" match {
      case digit( a) => println(a + " is Digit")
      case _ => println("it is something else")
    }
    

    more to read: http://www.scala-lang.org/api/2.12.1/scala/util/matching/index.html

    0 讨论(0)
  • 2020-12-23 11:51

    The answer is in the regex:

    val Digit = """^\d$""".r
    

    Then use the one of the existing methods.

    0 讨论(0)
提交回复
热议问题