如何在字符串中匹配secret_code_data:
xeno://soundcloud/?code=secret_code_data#
我试过了
val regex = Regex("""xeno://soundcloud/?code=(.*?)#""")
field = regex.find(url)?.value ?: ""
没有运气.我猜测 ?在代码可能成为问题之前,我应该以某种方式逃避它.你能帮我吗?
Jay*_*ard 39
这里有三个选项,第一个提供了一个很好的正则表达式,可以满足您的需要,另外两个用于解析URL,使用Regex替代正确处理URL组件编码/解码.
注意: 在大多数用例中,正则表达式方法是不安全的,因为它没有正确地将URL解析为组件,然后分别解码每个组件.通常,您无法将整个URL解码为一个字符串,然后安全解析,因为某些编码字符可能会在以后混淆正则表达式.这类似于使用正则表达式解析XHTML(如此处所述).请参阅下面的Regex替代方案.
这是一个清理正则表达式作为单元测试用例,可以安全地处理更多URL.在这篇文章的最后是一个单元测试,你可以使用每个方法.
private val SECRET_CODE_REGEX = """xeno://soundcloud[/]?.*[\?&]code=([^#&]+).*""".toRegex()
fun findSecretCode(withinUrl: String): String? =
        SECRET_CODE_REGEX.matchEntire(withinUrl)?.groups?.get(1)?.value
这个正则表达式处理这些情况:
/在路径中有和没有尾随请注意,在Kotlin中制作正则表达式的惯用方法是someString.toRegex().它和其他扩展方法可以在Kotlin API Reference中找到.
下面是使用的示例UriBuilder从Klutter库科特林.此版本处理编码/解码,包括Java标准URI类(有许多问题)未处理的更现代的JavaScript unicode编码.这是安全,简单的,您无需担心任何特殊情况.  
执行:
fun findSecretCode(withinUrl: String): String? {
    fun isValidUri(uri: UriBuilder): Boolean = uri.scheme == "xeno"
                    && uri.host == "soundcloud"
                    && (uri.encodedPath == "/" || uri.encodedPath.isNullOrBlank())
    val parsed = buildUri(withinUrl)
    return if (isValidUri(parsed)) parsed.decodedQueryDeduped?.get("code") else null
}
Klutter uy.klutter:klutter-core-jdk6:$klutter_version工件很小,包括一些其他扩展,包括现代化的URL编码/解码.($klutter_version使用最新版本).
这个版本稍微长一点,并且显示你需要自己解析原始查询字符串,解析后解码,然后找到查询参数:
fun findSecretCode(withinUrl: String): String? {
    fun isValidUri(uri: URI): Boolean = uri.scheme == "xeno"
            && uri.host == "soundcloud"
            && (uri.rawPath == "/" || uri.rawPath.isNullOrBlank())
    val parsed = URI(withinUrl)
    return if (isValidUri(parsed)) {
        parsed.getRawQuery().split('&').map {
            val parts = it.split('=')
            val name = parts.firstOrNull() ?: ""
            val value = parts.drop(1).firstOrNull() ?: ""
            URLDecoder.decode(name, Charsets.UTF_8.name()) to URLDecoder.decode(value, Charsets.UTF_8.name())
        }.firstOrNull { it.first == "code" }?.second
    } else null
}
这可以写成URI类本身的扩展:
fun URI.findSecretCode(): String? { ... }
在body中删除parsed变量并使用this因为你已经拥有了URI,所以你就是URI.然后拨打电话:
val secretCode = URI(myTestUrl).findSecretCode()
鉴于上述任何功能,运行此测试以证明其有效:
class TestSo34594605 {
    @Test fun testUriBuilderFindsCode() {
        // positive test cases
        val testUrls = listOf("xeno://soundcloud/?code=secret_code_data#",
                "xeno://soundcloud?code=secret_code_data#",
                "xeno://soundcloud/?code=secret_code_data",
                "xeno://soundcloud?code=secret_code_data",
                "xeno://soundcloud?code=secret_code_data&other=fish",
                "xeno://soundcloud?cat=hairless&code=secret_code_data&other=fish",
                "xeno://soundcloud/?cat=hairless&code=secret_code_data&other=fish",
                "xeno://soundcloud/?cat=hairless&code=secret_code_data",
                "xeno://soundcloud/?cat=hairless&code=secret_code_data&other=fish#fragment"
        )
        testUrls.forEach { test ->
            assertEquals("secret_code_data", findSecretCode(test), "source URL: $test")
        }
        // negative test cases, don't get things on accident
        val badUrls = listOf("xeno://soundcloud/code/secret_code_data#",
                "xeno://soundcloud?hiddencode=secret_code_data#",
                "http://www.soundcloud.com/?code=secret_code_data")
        badUrls.forEach { test ->
            assertNotEquals("secret_code_data", findSecretCode(test), "source URL: $test")
        }
    }
| 归档时间: | 
 | 
| 查看次数: | 24663 次 | 
| 最近记录: |