使用正则表达式和 grepl 检测以特定模式开头的单词

using regex and grepl to detect words starting with a specific pattern

我不明白为什么 grepl("see*", "file SEC", ignore.case = TRUE) returns TRUE?

我试图找到所有以 see 开头的单词,例如 Seeseeingseen 等,并将它们删除。 “file SEC”上面的字符串没有这个词,但返回TRUE

模式 "see*" 检查“se”后跟任意数量的 "e"s (e*)(包括零),因此“SE”匹配。

我相信你可能想研究类似这样的东西,不带“*”

grepl("^see", "file SEC", ignore.case = TRUE)

FALSE

除了“^”符号外,您还可以包含一个词边界\b,这样您就可以检测以该模式开头的词,但排除那些不以该模式开头的词,在多词字符中:

grepl("\bSee", c("file SEC", "See", "seeing", "seen", "he was seen", "He did not forsee the event"), ignore.case = TRUE)
[1] FALSE  TRUE  TRUE  TRUE  TRUE  FALSE

试试 grepl("^see", "file SEC") “^see”的意思是“所有以 see 开头的字符串”

其他人提到的问题是问题指定了 glob rather than a regular expression 或以不同的方式查看它指定了错误的正则表达式。

我们可以避免使用正则表达式和 glob,只使用固定字符串,方法是使用 startsWith 来测试字符串是否以固定的潜在子字符串开头。它不支持不区分大小写,但我们可以使用 tolower 来实现。

startsWith(tolower(c("file SEC", "seer", "a seer")), "see")
## [1] FALSE  TRUE FALSE