david hol david hol - 1 year ago 63
Scala Question

Get id number from URL approach

I have simple

and somewhere i have id that i want to get.
is inside this


So I want to get the number

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 Source

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))