Matching against a regular expression in Scala

前端 未结 4 954
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 02:52

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

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

Ouch. Scala has

相关标签:
4条回答
  • 2021-02-01 03:32

    I created a little "Pimp my Library" pattern for that problem. Maybe it'll help you out.

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

    Example of use

    scala> import RegexUtils._
    scala> """\w+""".r =~ "foo"
    res12: Boolean = true
    
    0 讨论(0)
  • 2021-02-01 03:36

    I usually use

    val regex = "...".r
    if (regex.findFirstIn(text).isDefined) ...
    

    but I think that is pretty awkward.

    0 讨论(0)
  • 2021-02-01 03:42

    Currently (Aug 2014, Scala 2.11) @David's reply tells the norm.

    However, it seems the r."..." string interpolator may be on its way to help with this. See How to pattern match using regular expression in Scala?

    0 讨论(0)
  • 2021-02-01 03:47

    You can define a pattern like this :

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

    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
    

    You could even extract :

    scala> val Email(name, domain) = "test@example.com"
    name: String = test
    domain: String = example.com
    

    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
    

    Hope this will help.

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