Kotlin中的正则表达式匹配

时间:2016-01-04 15:35:28

标签: regex kotlin

如何匹配字符串中的secret_code_data:

xeno://soundcloud/?code=secret_code_data#

我已经尝试了

val regex = Regex("""xeno://soundcloud/?code=(.*?)#""")
field = regex.find(url)?.value ?: ""
没有运气。我猜测 ?在代码可能是问题之前,我应该以某种方式逃避它。你能帮忙吗?

2 个答案:

答案 0 :(得分:39)

这里有三个选项,第一个提供了一个很好的正则表达式,它可以满足您的需要,另外两个用于解析URL,使用Regex替代正确处理URL组件编码/解码。

使用Regex进行解析

注意: 正则表达式方法在大多数用例中都不安全,因为它没有正确地将URL解析为组件,然后分别解码每个组件。通常,您无法将整个URL解码为一个字符串,然后安全解析,因为某些编码字符可能会在以后混淆正则表达式。这类似于使用正则表达式解析XHTML(作为described here)。请参阅下面的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或类似的类

进行解析

以下是使用UriBuilder中的Klutter library for Kotlin的示例。此版本处理encoding/decoding,包括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,请使用most current release)。

使用JDK URI Class

进行解析

此版本稍长一些,显示您需要自己解析原始查询字符串,解析后解码,然后找到查询参数:

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? { ... }

在正文中移除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")
        }
    }

答案 1 :(得分:0)

在第一个问号之前添加转义,因为它具有特殊含义

? 

变为

\?

您还在第一组中捕获密码。不确定后面的kotlin代码是否正在提取第一组。