|是否提供了一个字符串来检测|
name = "KKSWAP"
stringr::str_starts(name, "RTT|SWAP")
返回TRUE,但是
str_starts(name, "SWAP|RTT")
返回FALSE
这种行为似乎是错误的,因为KKSWAP不是以"RTT"或"SWAP"开头的.我认为这两种情况都是错误的.
|是否提供了一个字符串来检测|
name = "KKSWAP"
stringr::str_starts(name, "RTT|SWAP")
返回TRUE,但是
str_starts(name, "SWAP|RTT")
返回FALSE
这种行为似乎是错误的,因为KKSWAP不是以"RTT"或"SWAP"开头的.我认为这两种情况都是错误的.
原因可在函数代码中找到:
function (string, pattern, negate = FALSE)
{
switch(type(pattern), empty = , bound = stop("boundary() patterns are not supported."),
fixed = stri_startswith_fixed(string, pattern, negate = negate,
opts_fixed = opts(pattern)), coll = stri_startswith_coll(string,
pattern, negate = negate, opts_collator = opts(pattern)),
regex = {
pattern2 <- paste0("^", pattern)
attributes(pattern2) <- attributes(pattern)
str_detect(string, pattern2, negate)
})
}
您可以看到,它将"^"粘贴在parttern前面,因此在您的示例中,它会查找"^RR | SWAP"并找到"SWAP".
如果要查看多个图案,应使用矢量:
name <- "KKSWAP"
stringr::str_starts(name, c("RTT","SWAP"))
# [1] FALSE FALSE
如果你只想要一个答案,你可以加上any()
个
name <- "KKSWAP"
stringr::str_starts(name, c("RTT","SWAP"))
# [1] FALSE
stringr::str_starts()
的优点是模式参数的矢量化,但如果您不需要它,正如TTS所建议的那样,grepl('^RTT|^SWAP', name)
是一个很好的base R替代方案.
或者,jpsmith建议的基函数startsWith()
同时提供矢量化和|选项:
startsWith(name, c("RTT","SWAP"))
# [1] FALSE FALSE
startsWith(name, "RTT|SWAP")
# [1] FALSE