【问题标题】:How to use regex to find a keyword in Kotlin如何使用正则表达式在 Kotlin 中查找关键字
【发布时间】:2020-06-22 11:52:00
【问题描述】:
fun main () {

    val keyWords = listOf<String>("plus", "minus",
        "divided by", "multiplied by", "what is")

    val userInput : String? = readLine()
    val rx = Regex( "\\W${keyWords.joinToString(separator = "|")}")
    val result = keyWords

    if (rx.matches(userInput)){
        print("True")
    }
}

我不断收到类型不匹配的错误,并且它需要一个 Char 序列。我尝试了不同的方法,但仍然无法找到解决方案。

帮帮我,欧比旺克诺比,你是我唯一的希望

【问题讨论】:

  • 问题通过语法突出显示立即可见,您在字符串文字中使用",编程语言应该如何知道字符串文字的结束位置?您需要转义它们或使用原始字符串
  • ${}表达式中使用"没有问题。
  • @Chase ${} 中的代码是原始代码,不会干扰任何字符串。

标签: regex kotlin


【解决方案1】:

有几个问题需要解决:

  • 由于userInput 可以为空,你应该确保你没有将null 值传递给只需要CharSequence 的正则表达式引擎
  • .matches() 方法需要一个完整的字符串匹配,你的正则表达式只匹配一个字符串的一部分,所以你需要使用Regex#containsMatchIn
  • 模式开头的\W 只需要在第一个替代项之前使用非单词字符。它也不允许在字符串的开头进行匹配。您需要使用 \b(?:...)\b 来包装您的替代品。

固定 Kotlin sn-p:

if (userInput != null) {
  val rx = Regex( "\\b(?:${keyWords.joinToString(separator = "|")})\\b")
  print (rx.containsMatchIn(userInput))
}

如果您的keyWords 可以包含特殊字符,您将需要escape special characters,然后使用明确的单词边界

val rx = Regex( "(?<!\\w)(?:${keyWords.map{Regex.escape(it)}.joinToString("|")})(?!\\w)")

空白边界

val rx = Regex( "(?<!\\S)(?:${keyWords.map{Regex.escape(it)}.joinToString("|")})(?!\\S)")

【讨论】:

  • wiktor 你是一个救生员,真的帮了我很多谢谢
【解决方案2】:

问题在于 userInput 可以为空。

10:20: error: type mismatch: inferred type is String? but CharSequence was expected
    if (rx.matches(userInput)){

String 实现 CharSequence

解决这个问题的一种方法是检查null

val userInput : String? = readLine()
if (userInput != null) {
    val rx = Regex( "\\W${keyWords.joinToString(separator = "|")}")
    val result = keyWords
    if (rx.matches(userInput)){
        print("True")
    }
}

【讨论】:

  • 感谢您回复解决方案消除了错误,但现在打印不正确。发生这种情况有什么原因吗?我该如何防止这种情况发生。
猜你喜欢
  • 1970-01-01
  • 2011-05-20
  • 2018-08-10
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2015-05-26
相关资源
最近更新 更多