Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Kotlin检查字符串中的单词_Android_Regex_Kotlin - Fatal编程技术网

Android Kotlin检查字符串中的单词

Android Kotlin检查字符串中的单词,android,regex,kotlin,Android,Regex,Kotlin,我有一个NSFW类,它根据已知NSFW单词列表扫描项目名称和描述等文本 这将是测试字符串列表的最佳方法,如 let nsfw = listof( "badword", "curseword", "ass", ... 200+ more ) 针对以下字符串: This is the text that contains a badword // returns true 请注意,我需要检查完整的单词。不是文字的一部分 因此,这句话: The gr

我有一个NSFW类,它根据已知NSFW单词列表扫描项目名称和描述等文本

这将是测试字符串列表的最佳方法,如

    let nsfw = listof(
    "badword",
    "curseword",
    "ass",
    ... 200+ more
    )
针对以下字符串:

This is the text that contains a badword // returns true
请注意,我需要检查完整的单词。不是文字的一部分

因此,这句话:

The grass is grean // returns false
因为草不是一个坏词

我试过这样的方法,但没有检查完整的单词

        val result =  nsfw.filter { it in sentence.toLowerCase() }
您可以在要检查的字符串上使用空格作为分隔符,以便创建其单词列表,尽管这并不总是保证所有单词都能成功提取,因为可能存在点或逗号等其他单词分隔符。如果适合您,请执行以下操作:

val nsfw = listOf(
    "badword",
    "curseword",
    "ass"
)

val str = "This is the text that contains a badword"
val words = str.toLowerCase().split("\\s+".toRegex())
val containsBadWords = words.firstOrNull { it in nsfw } != null
println(containsBadWords)
将打印

true
如果您想要一份“坏词”列表:


您可以构建一个类似regex的

\b(?:word1|word2|word3...)\b
看。然后,将其与以下内容一起使用:

这里,
nsfw.joinToString(separator=“|”)将单词与管道(交替操作符)连接起来,
“\\b(?:${nsfw.joinToString(separator=“|”)将创建正确的正则表达式

如果您的单词可能包含特殊的正则表达式元字符,如
+
)等,则需要使用以下命令对
nsfw
值进行“预处理”:

还有一件事:如果关键字可能以字母、数字和下划线以外的字符开头/结尾,则不能依赖
\b
单词边界。你可以


  • 使用空白边界:
    val rx=Regex(“(?可能重复检查此帖子:多好的答案,感谢您花时间使其如此先进
    
    \b(?:word1|word2|word3...)\b
    
    val nsfw = listOf(
        "badword",
        "curseword",
        "ass"
    )
    val s1 = "This is the text that contains a badword"
    val s2 = "The grass is grean"
    val rx = Regex("\\b(?:${nsfw.joinToString(separator="|")})\\b")
    println(rx.containsMatchIn(s1)) // => true
    println(rx.containsMatchIn(s2)) // => false
    
    val rx = Regex("\\b(?:${nsfw.map{Regex.escape(it)}.joinToString("|")})\\b")
                                ^^^^^^^^^^^^^^^^^^^^^^