Manu Chadha Manu Chadha - 21 days ago 10
Scala Question

$ not working in regex in Scala

Am I correct that

$
is used to match an expression starting from end of a string (opposite to
^
which matches from beginning of the string)?

The
^
is working fine

scala> val reg = "^(abc)".r
reg: scala.util.matching.Regex = ^(abc)

scala> reg findFirstIn "hello abc hanu"
res44: Option[String] = None

scala> reg findFirstIn "abc hello abc hanu"
res45: Option[String] = Some(abc)


But
$
isn't

scala> val reg = "$(abc)".r
reg: scala.util.matching.Regex = $(abc)

scala> reg findFirstIn "abc hello abc hanu"
res46: Option[String] = None

scala> reg findFirstIn "abc hello abc hanu abc"
res47: Option[String] = None


Why?

Answer Source

$ matches end of input, so $(abc) means go to the end of the input, then find abc after the end. This obviously would never match anything.

Did you maybe mean (abc)$ meaning find (abc) just before the end (instead of after)?