0

for example:

I have the following string

"somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

so the number is always between

theStringBeforeTheNumber{number}theStringAfterTheNumber

What I want is to extract the number from the whole string, how can I do that? im using scala how should my regex look like? val myRgx: Regex = """myRegexGoesHere""".r

jack miao
  • 1,398
  • 1
  • 16
  • 32

3 Answers3

1

You can use your suggested pattern, slightly modified as:

val string = "theStringBeforeTheNumber20.47theStringAfterTheNumber"
val pattern = """theStringBeforeTheNumber(.*?)theStringAfterTheNumber""".r
pattern.findAllIn(string).matchData foreach {
    m => println(m.group(1))
}

The quantity in parentheses (.*?) is a capture group and it uses a lazy dot. This says to match everything between the first string and the first occurrence of the second string. We print out the first capture group in the code snippet.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

If you know the starting and finish string, I think that is better do a substring() because in general the regexp is costly. For example substring(indexOf(theStringBeforeTheNumber) + length(theStringBeforeTheNumber) , indexOf(theStringAfterTheNumber)) Also you must consider if the initial and final string are equals because the indexes, in that case you have do some extra calculation. Hope this help.

Luis Carlos
  • 345
  • 3
  • 10
1

Here's another approach using Regex along with verifying the extracted number:

import scala.util.Try

val s = "somestringthatcanbeanything theStringBeforeTheNumber20.47theStringAfterTheNumber somestringthatcanbeanything"

val pattern = """.*?theStringBeforeTheNumber([0-9.-]*)theStringAfterTheNumber.*""".r

val number: Double = s match {
  case pattern(num) => Try(num.toDouble).getOrElse(-999)
  case _ => -999
}
number: Double = 20.47
Leo C
  • 22,006
  • 3
  • 26
  • 39