Skyline
Skyline

Reputation: 53

How to findall expressions to a word in kotlin?

fun main(args: Array<String>) {
    val text = " \"id\": \"5jaq2\", \"mood\"  \"id\": \"RKlvj\", \"is_verified\"  \"id\": \"XPyZj\", \"mood\""
    val regex = Regex("id\": (.*?)[,]")
    val matches = regex.findAll(text)
    val names = matches.map { it.groupValues[1] }.toList()
    println(names)
}

I want to find all the id's but if "is_verified" is after id, I dont want to put it in a list.

Current result: ["5jaq2", "RKlvj", "XPyZj"]

Expected: ["5jaq2", "XPyZj"]

Any idea how to do this correctly?

Upvotes: 1

Views: 287

Answers (1)

GuilhermeMagro
GuilhermeMagro

Reputation: 321

Try with:

val regex = Regex("(?:\"id\":\\s)([\"\\w\\d]*?)(?:,\\s)(?!\"is_verified\")")

Explanation:

(?:\"id\":\\s)      // Non-capturing group to match {"id": }
([\"\\w\\d]*?)      // Capturing group to catch only words, digits and quotation marks characters
(?:,\\s)            // Non-capturing group to match {, }
(?!\"is_verified\") // Negative lookahead to not match if the next letters are {"is_verified"} 

Tests: https://regexr.com/6inod

Upvotes: 2

Related Questions