3

I am learning Scala and spark and want to get the numbers out of string. And for that i am using the regular expression. And came to know about the weird signature of using regular patterns in Scala.

Here is my code:

val myString: String = "there would be some number here 34."
val pattern = """.* ([\d]+).*""".r  
val pattern(numberString) = myString
val num = numberString.toInt
println(answer)

The code is working fine, but seems a bit weird and less readable.

Is there any other way to do this in Scala? Or any other syntax which i can use?

1
  • Well, I am going through a similar tutorial and I am unable to grasp my mind around this syntax. It feels pretty weird to see the result part be part of a function call? val pattern(numberString) = myString. Could anyone explain that? Commented Sep 18, 2021 at 11:08

1 Answer 1

2

The pattern-matching way you are extracting the number is rather resource consuming: since the pattern must match the whole string, you have to add .* on both ends of the regex, and that triggers a lot of backtracking. You also added a space to make sure the first .* does not eat all the digits on the left and return all 1+ digits found.

If you are looking for a first match, use findFirstIn:

val myString: String = "there would be some number here 34."
val numberString = """\d+""".r.findFirstIn(myString)
val num = numberString.get.toInt
println(num) // => 34

See the Scala demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.