Manu Chadha Manu Chadha - 20 days ago 8
Scala Question

Can I get the whole word against which the regex matched

In the following code, is there a way to get the whole string

hello
instead of
Some(h)
. I want to get the word/string for which the regex matched.

scala> val reg = "h".r
reg: scala.util.matching.Regex = h

scala> reg findFirstIn "hello handsome"
res48: Option[String] = Some(h)

Answer Source

If you want to capture the word starting with h you have to change the regex. Something like this,

  scala> val reg = """h\w+""".r
  reg: scala.util.matching.Regex = h\w+

  scala> reg findFirstIn "hello handsome"
  res4: Option[String] = Some(hello)

  scala> reg findFirstIn "random handsome"
  res5: Option[String] = Some(handsome)

  scala> reg findFirstIn "random person"
  res6: Option[String] = None

In above regex h\w+ captures the word starting with h.