替换 R 中字符串中第一次出现的字符

Art*_*Sbr 0 string r gsub

我正在使用很多字符串。我意识到我可以使用它们来阅读它们read.table(),但我必须事先清理它们。

我有这样的一般结构:

Request(123): \n Element1: 123123 \n Element2: 456456
Run Code Online (Sandbox Code Playgroud)

我只想删除第一次出现的分号:,而不删除其余的分号。

Request(123) \n Element1: 123123 \n Element2: 456456
Run Code Online (Sandbox Code Playgroud)

让第一个字符串存储在 中test。阅读了几个线程后,我尝试了.*

gsub(pattern = ".*:", replacement = "", x = test)
Run Code Online (Sandbox Code Playgroud)

我知道你可以使用问号来使搜索变得“懒惰”,但我无法让它工作。

Gre*_*gor 9

in代表global,表示它将匹配所有出现的情况g。如果您使用not ,则仅匹配和替换第一个出现的位置。详细信息请参见说明gsubsubgsub?gsub

subgsub分别对第一个和所有匹配项进行替换。

而且,如果您只想替换冒号,则您的模式应该是":",".*:"将匹配并替换最后一个冒号之前的所有内容。如果您想替换第一个冒号之前的所有内容,请使用sub?使其*不贪婪。

x = "Request(123): \n Element1: 123123 \n Element2: 456456"

## match everything up through last colon
sub(".*:", "", x)
# [1] " 456456"

## not greedy, match everything up through first colon
sub(".*?:", "", x)
# [1] " \n Element1: 123123 \n Element2: 456456"

## match first colon only
## since we don't need regex here, fixed = TRUE will speed things up
sub(":", "", x, fixed = TRUE)
#[1] "Request(123) \n Element1: 123123 \n Element2: 456456"

## compare to gsub, match every colon
gsub(":", "", x, fixed = TRUE)
# [1] "Request(123) \n Element1 123123 \n Element2 456456"
Run Code Online (Sandbox Code Playgroud)