如何在 Kotlin 中检查字符串是否包含给定正则表达式并以给定正则表达式开头?
我期待我可以这样做:
fun main(args: Array<String>) {
var text = "test string"
val regex = Regex.fromLiteral("^test")
val matches: Boolean = text.contains(regex)
assert(matches)
}
但这不起作用。它按预期工作,无需 ^。甚至做matches
或find
,或正则表达式运算符,如 containsMatchIn似乎不起作用。
我是否遗漏了一些明显的东西?也许我不能使用开始边界,或者我不应该使用它。
注意:我知道 startsWith但这不允许我使用正则表达式。我想使用正则表达式,因为我的代码具有比“测试字符串”更复杂的字符串。
最佳答案
Regex.fromLiteral("^test")
生成与 ^test
匹配的 \^test
正则表达式code> 子字符串迭代。检查Regex.fromLiteral()
文档:
Returns a literal regex for the specified literal string.
您只需根据字符串文字创建一个正则表达式,使用
val regex = """^test""".toRegex()
请参阅Kotlin demo .
关于android - 如何在 kotlin 正则表达式语句中使用正则表达式开始标记 (^),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540788/