https://kotlinlang.org logo
#getting-started
Title
# getting-started
o

oday

03/11/2022, 2:00 PM
how can i get back these variables to use them?
"ticket-alert/remove/(?<id>.+)/(?<hash>.+)".toRegex()
id and hash
t

Ties

03/11/2022, 2:06 PM
Copy code
"ticket-alert/remove/(?<id>.+)/(?<hash>.+)".toRegex().matchEntire("")
And now you have a MatchResult? which contains your matching groups
just did a google: https://www.baeldung.com/kotlin/regular-expressions this explains most things quite well 🙂
o

oday

03/11/2022, 2:08 PM
yea I was here too, didnt scroll down enough i guess
thanks
t

Ties

03/11/2022, 2:09 PM
no worries 🙂 good luck
o

oday

03/11/2022, 2:31 PM
ok so another thing, do you know how I can translate this to koltin if you get the gist of whats going on here?
Copy code
routes = mapOf(
    '/ticket-alert/remove/(?<id>.+)/(?<hash>.+)' to (id, hash) => RemoveTicketAlertByHashLaunchAction(ticketAlertId=id, ticketAlertHash = hash)
)
I want to basically match the pattern and return the variables I got to the value side of the map
basically..
yea no need for that actually
n

nkiesel

03/11/2022, 8:18 PM
Copy code
fun extract(s: String): Map<String, String> {
    val regex = "ticket-alert/remove/([^/]+)/([^/]+)".toRegex()
    val (id, hash) = regex.matchEntire(s)?.destructured ?: throw IllegalArgumentException()
    return mapOf("id" to id, "hash" to hash)
}
Though I generally dislike returning maps from such functions:
Copy code
data class TicketAlert(val id: String, val hash: String) {
    companion object {
    	val regex = """ticket-alert/remove/([^/]+)/([^/]+)""".toRegex()    

        fun extract(s: String): TicketAlert {
	    	val (id, hash) = regex.matchEntire(s)?.destructured ?: throw IllegalArgumentException()
    	    return TicketAlert(id, hash)
    	}
	}
}