Matching against a regular expression in Scala

前端 未结 4 958
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    

提交回复
热议问题