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?
source to share
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")
source to share
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.
source to share
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
.
source to share