如何从表达式后面的字符串中提取 7 或 8 个元素? 例如:
text <- "Hello World! My name is Sam!"
expression <- "World!"
如何提取表达式 + 接下来的 x 元素(比如 8(?所以结果看起来像这样:
result <- "World! My name"
谢谢。
这是一个基本的 R 方法,带有sub
sub(paste0(".*(", expression, ".{8}).*"), "\1", text)
[1] "World! My name"
paste0(".*(", expression, ".{8}).*")
返回正则表达式 ".*(World!.{8}).*"其中
".*"匹配任何类型的一个或多个字符,"(("是捕获括号,"World!"是文字,".{8}" 匹配接下来的 8 个字符。
正如注释中@mt1022指出的那样,我们可以使用另一组正则表达式函数regmatches
和regexpr
来执行子字符串的提取。
regmatches(text, regexpr(paste0(expression, '.{8}'), text))
[1] "World! My name"
regexpr
返回与表达式匹配的子字符串的索引,regmatches
从字符向量中提取这些子字符串。
text <- "Hello World! My name is Sam!"
expression <- "World!"
n=8
ind = unlist(gregexpr(pattern =expression,text))[1]
substr(text,ind,ind+nchar(expression)+n-1)
其中 n 是附加字符的数量。它返回:
"World! My name"
希望这有帮助!