Scala regex with $ (end of line)

I'm a little bit confused. (I'm a pro in regexps but haven't really used them in scala / java). I have a numeric string of 11 characters in length, it only needs 10, so:

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

      

He gives MatchError

, but why ?! What have I misunderstood?

+3


source to share


3 answers


Since you have 11 digits, not 10. You can set "10 or more" with {10,}

. To only match the end of a line, you need to explicitly specify the full pattern:

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

      



Update: as long as you are not on Scala 2.10 and you can use Daniel unanchored

, you can work around it like this:

Pattern.findFirstIn("79283767219")

      

+7


source


If a regex pattern is matched, the regex pattern must match the entire string. That is, it looks like a regular expression pattern starting with ^

and ending with $

. The reason for this is that a match

must deconstruct the entire left side from the right side.

As of Scala 2.10, you can call unanchored

to get a match that will do partial matches, for example:



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

      

Be sure your anchor will be saved. It's just an expectation that a match should be applied across the entire line to be removed.

+10


source


Remember that an instance is used Pattern

in , for example , this is not a search, this is a match! This means that it must match the entire value agreed upon (called in Scala parlance, "scrutinee" in your example).match

RegEx

Pattern

79283767219

This explains why your example got MatchError

.

+3


source







All Articles