我正在使用正则表达式在 Kotlin 中创建一种方法,该方法检查字符串是否包含一个或多个特定代词(例如“我”、“我们”、“你”等)。例如,“我们是一家科技公司”应该是匹配项,“Web 是给蜘蛛的”不应该是匹配项。
我尝试使用此代码:
fun main() {
val text = "We are testing!"
val regex = "/\b(i|you|we)\b/g".toRegex()
if (regex.containsMatchIn(text.lowercase())) {
println("match")
} else {
println("no match")
}
}
,但它打印“不匹配”。
Kotlin(和 Java)正则表达式是用字符串字面量定义的,而不是正则表达式字面量,即当您/
在模式的开头和/g
(或只是/
)末尾添加时,实际上是将它们添加到模式 string 中。
您可以使用以下修复程序:
val text = "We are testing!"
val regex = """(?i)\b(i|you|we)\b""".toRegex()
if (regex.containsMatchIn(text)) {
println("match")
} else {
println("no match")
}
该"""(?i)\b(i|you|we)\b"""
等于"(?i)\\b(i|you|we)\\b"
,前者治疗反斜杠作为文字字符。
请注意,您不需要使用.lowercase()
,(?i)
不区分大小写的修饰符将使匹配不区分大小写。
请参阅在线 Kotlin 演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句