david hol david hol - 3 months ago 17
Scala Question

Get id number from URL approach

I have simple

URL
and somewhere i have id that i want to get.
This
id
is inside this
string
:

...&userId=123&...


So I want to get the number
123
.

This is what I tried:

val url = "......"
val value = array.find(x => x.startsWith("userId="))
val id = value.get.replace("userId=", "")


Any other suggestions or this is the best approach?

Answer

I don't Scala but what you are trying to do doesn't make sense to me. So if you like to do it with RegExes then this would be your choice. A good choice actually:

Live demo

import scala.util.matching.Regex

object Main extends App {
    val url = "https://example.com/?foo=bar&userId=4523&foo=baz"
    val pattern = new Regex("userId=(\\d+)")
    pattern.findFirstMatchIn(url) match {
        case Some(m) => println(m.group(1))
    }
}