Regex 在R中的grep函数中使用正则表达式
如果Regex 在R中的grep函数中使用正则表达式,regex,r,Regex,R,如果x和y是随机字符,任何人都可能知道如何使用grep函数(不使用stringi包)从该字符中提取x和y? 我对正则表达式非常不熟练。 感谢您的回复。此处的正则表达式匹配任何字符“和”字符,然后使用regmatches提取它们: txt <- c("x and y", "a and b", " C and d", "qq and rr") matches <- regexec("([[:alpha:]]+)[[:blank:]]+and[[:blank:]]+([[:alpha:
x
和y
是随机字符,任何人都可能知道如何使用grep
函数(不使用stringi
包)从该字符中提取x
和y
?
我对正则表达式非常不熟练。
感谢您的回复。此处的正则表达式匹配任何字符“和”字符,然后使用
regmatches
提取它们:
txt <- c("x and y", "a and b", " C and d", "qq and rr")
matches <- regexec("([[:alpha:]]+)[[:blank:]]+and[[:blank:]]+([[:alpha:]]+)", txt)
regmatches(txt, matches)[[1]][2:3]
## [1] "x" "y"
regmatches(txt, matches)[[2]][2:3]
## [1] "a" "b"
regmatches(txt, matches)[[3]][2:3]
## [1] "C" "d"
regmatches(txt, matches)[[4]][2:3]
## [1] "qq" "rr"
txt正如@MrFlick评论的那样,grep
不是提取这些子字符串的正确函数
您可以使用regmatches
执行以下操作:
> x <- c('x and y', 'abc and def', 'foo and bar')
> regmatches(x, gregexpr('and(*SKIP)(*F)|\\w+', x, perl=T))
# [[1]]
# [1] "x" "y"
# [[2]]
# [1] "abc" "def"
# [[3]]
# [1] "foo" "bar"
嗯,grep
匹配整个字符串,而不是字符串的一部分。因此,如果要同时提取x
和y
,这可能不是正确的函数。您感兴趣的两个值是否总是以“和”分隔?如果这样做,使用strsplit
可能更有意义。例如:strsplit(“x和y”,“and”)[[1]]
@MrFlick,我觉得和只是一个例子,他在寻找一个更通用的解决方案。但我可能错了though@MrFlick谢谢这总是由“和”分隔,这是htest.object$data.name的结果。
@DavidArenburg正如我读到的,“和”似乎是常量,“x”和“y”是随机的。要编写只需要一个(坏的)样本输入就可以概括的有用代码是不可能的。希望OP能提供更多有用的测试用例。@Flick先生,是的,根据他的评论,你似乎是对的。哦,好吧。。。
> x <- c('x and y', 'abc and def', 'foo and bar')
> strsplit(x, ' and ', fixed=T)
# [[1]]
# [1] "x" "y"
# [[2]]
# [1] "abc" "def"
# [[3]]
# [1] "foo" "bar"