假设我运行以下
txt <- "client:A, field:foo, category:bar"
grep("field:[A-z]+", txt, value = TRUE, perl = TRUE)
Run Code Online (Sandbox Code Playgroud)
基于regexr.com我希望我会得到field:foo,但我得到了整个字符串。为什么是这样?
您似乎想提取该值。使用regmatches:
txt <- "client:A, field:foo, category:bar"
regmatches(txt, regexpr("field:[[:alpha:]]+", txt))
# => [1] "field:foo"
Run Code Online (Sandbox Code Playgroud)
请参阅R 演示。
要匹配多次出现,请替换regexpr为gregexpr。
或使用stringr str_extract_all:
library(stringr)
str_extract_all(text, "field:[a-zA-Z]+")
Run Code Online (Sandbox Code Playgroud)
还有一点就是[A-z]匹配多个ASCII字母。使用[[:alpha:]]在TRE(regexpr/gregexpr无perl=TRUE)/ ICU(stringr)正则表达式匹配任何字母。