Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala regular expression with $ (end of string)

Tags:

regex

scala

I'm somewhat in difficulty. (I'm pro in regexps but not much used them in scala/java). I have numeric string of 11 chars in length, need just last 10, so:

val Pattern = """(\d{10})$""".r
"79283767219" match {
  case Pattern(m) => m
}

It gives MatchError, but why?! What have I misunderstood?

like image 985
dmitry Avatar asked Nov 30 '22 13:11

dmitry


1 Answers

When you match against a regex pattern, the regex pattern should match the whole string. That is, it's like the regex pattern started with ^ and ended with $. The reason behind this is that a match is supposed to deconstruct the whole of the left side on the right side.

With Scala 2.10, you can call unanchored to get a matcher that will do partial matches, like this:

val Pattern = """(\d{10})$""".r.unanchored

Be assured that your anchor will be preserved. It's just the expectation that the match should apply over the whole string that will be dropped.

like image 184
Daniel C. Sobral Avatar answered Dec 28 '22 02:12

Daniel C. Sobral