如何在 kotlin 中查找某个单词的所有表达式?

发布于 2025-01-18 13:08:10 字数 481 浏览 3 评论 0原文

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

我想找到所有ID的ID,但是如果“ IS_Verified”在ID之后,我不想将其放入列表中。

当前结果: [“ 5JAQ2”,“ RKLVJ”,“ XPYZJ”]

期望: [“ 5JAQ2”,“ XPYZJ”]

任何想法如何正确执行此操作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏至、离别 2025-01-25 13:08:10

尝试:

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

说明:

(?:\"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"} 

测试: https://regexr.com/6inod

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文