Gsub a every element after a keyword in R 中的关键字

Gsub a every element after a keyword in R

我想删除某个关键字后的字符串的所有元素。 示例:

this.is.an.example.string.that.I.have

期望的输出:

This.is.an.example

我试过使用 gsub('string', '', list) 但这只会删除字符串。我也尝试过使用 gsub('^string', '', list) 但这似乎也不起作用。

谢谢。

以下简单的sub可能会对您有所帮助。

sub("\.string.*","",variable)

说明:使用方法sub

sub(regex_to_replace_text_in_variable,new_value,variable)

subgsub的区别:

sub: 用于对变量进行替换。

gsubgsub 仅用于相同的替换任务,但它只会对找到的所有匹配项执行替换,尽管 sub 仅对找到的第一个匹配项执行替换.

来自的帮助页面 R:

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

您可以试试这个积极的回顾正则表达式

S <- 'this.is.an.example.string.that.I.have'
gsub('(?<=example).*', '', S, perl=TRUE)
# 'this.is.an.example'

您可以使用 strsplit。在这里,您在关键字后拆分字符串,并保留字符串的第一部分。

x <- "this.is.an.example.string.that.I.have"
strsplit(x, '(?<=example)', perl=T)[[1]][1]

[1] "this.is.an.example"