Kotlin 正则表达式边界匹配不工作
Kotlin Regex Boundary Matching Not working
我正在尝试解析一个单词,两侧以空格或标点符号为界。
我试过这个:
fun main(args: Array<String>) {
val regex = "\bval\b".toRegex();
regex.matches("fn foo() { val x = 2;} x;").also { println(it) }
}
但这打印出错误。我在这里 https://regex101.com/r/vNBefF/2 测试了正则表达式,它可以工作,与输入字符串匹配。
我做错了什么?
我认为你用错了方法。来自 KotlinDoc:
Indicates whether the regular expression matches the entire input.
我想你可能想要的是containsMatchIn. You can play with this on the playground。
我正在尝试解析一个单词,两侧以空格或标点符号为界。
我试过这个:
fun main(args: Array<String>) {
val regex = "\bval\b".toRegex();
regex.matches("fn foo() { val x = 2;} x;").also { println(it) }
}
但这打印出错误。我在这里 https://regex101.com/r/vNBefF/2 测试了正则表达式,它可以工作,与输入字符串匹配。
我做错了什么?
我认为你用错了方法。来自 KotlinDoc:
Indicates whether the regular expression matches the entire input.
我想你可能想要的是containsMatchIn. You can play with this on the playground。