string 带有 str_detect R 的多个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35962426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple strings with str_detect R
提问by Magick.M
I want to find multiple strings and put it in a variable, however I keep getting errors.
我想找到多个字符串并将其放入一个变量中,但是我不断收到错误消息。
queries <- httpdf %>% filter(str_detect(payload, "create" || "drop" || "select"))
Error: invalid 'x' type in 'x || y'
queries <- httpdf %>% filter(str_detect(payload, "create" | "drop" | "select"))
Error: operations are possible only for numeric, logical or complex types
queries1 <- httpdf %>% filter(str_detect(payload, "create", "drop", "select"))
Error: unused arguments ("drop", "select")
None of these worked. Is there another way to do it with str_detect
or should i try something else? I want them to show up as in the same column as well.
这些都没有奏效。有没有其他方法可以做到,str_detect
或者我应该尝试其他方法吗?我希望它们也显示在同一列中。
回答by fabilous
An even simpler way, in my opinion, for your quite short list of strings you want to find can be:
在我看来,对于您要查找的非常短的字符串列表,更简单的方法可以是:
queries <- httpdf %>% filter(str_detect(payload, "create|drop|select"))
As this is actually what
因为这实际上是什么
[...]
paste(c("create", "drop", "select"),collapse = '|'))
[...]
[...]
paste(c("create", "drop", "select"),collapse = '|'))
[...]
does, as recommended by @penguin before.
确实,正如@penguin 之前所推荐的那样。
For a longer list of strings you want to detect I would first store the single strings into a vector and then use @penguin's approach, e.g.:
对于要检测的较长字符串列表,我首先将单个字符串存储到向量中,然后使用 @penguin 的方法,例如:
strings <- c("string1", "string2", "string3", "string4", "string5", "string6")
queries <- httpdf %>%
filter(str_detect(payload, paste(strings, collapse = "|")))
This has the advantage that you can easily use the vector strings
later on as well if you want to or have to.
这样做的好处是,strings
如果您愿意或必须,您以后也可以轻松地使用该向量。
回答by penguin
This is a way to solve this problem:
这是解决此问题的一种方法:
queries1 <- httpdf %>%
filter(str_detect(payload, paste(c("create", "drop", "select"),collapse = '|')))