gsub 用退格键替换模式
gsub replace pattern with backspace
我有一个数据集,其中有一列包含带有年份的标签 (OldLabel
),我想制作另一列只包含标签,而不包含年份 (NewLabel
).我写了下面的代码,但它在新标签的末尾留下了一个 space。
data["NewLabel"] <- gsub("20..", "", data$OldLabel)
#removes any part of the OldLabel column that starts with 20 and ends with 2 digits, e.g: 2011 or 2008
有没有办法让 gsub 用后面的 space 替换序列,这样它就可以在它替换的那一年左右摆脱任何 spaces ?我尝试使用 "\b"
作为我的替换文本,但只是用 b
代替了它,而不是后面的 space.
编辑:根据请求,OldLabel
的一个例子是 "Valley Summer 2014"
,它应该变成 "Valley Summer"
,但最终是 "Valley Summer "
我当前的代码。然而,有些也可能是 2012 Valley Summer
的形式,所以我认为简单地在模式中包含 space 是不够稳健的。
试试这个:
data["NewLabel"] <- gsub("[ ]{0,1}20[[:digit:]]{2}[ ]{0,1}", "", data$OldLabel)
成对的花括号是重复量词,其范围由一个(精确)值或两个(最小值和最大值)值确定。有关详细信息,请参阅 ?regex
。 (您不想用退格字符替换它们。)
test <- c("2012 Valley Summer", "Valley Summer 2014")
gsub("[ ]{0,1}20[[:digit:]]{2}[ ]{0,1}", "", test)
#[1] "Valley Summer" "Valley Summer"
data["NewLabel"] <- gsub("\s*[0-9]\s*", "", data$OldLabel)
我有一个数据集,其中有一列包含带有年份的标签 (OldLabel
),我想制作另一列只包含标签,而不包含年份 (NewLabel
).我写了下面的代码,但它在新标签的末尾留下了一个 space。
data["NewLabel"] <- gsub("20..", "", data$OldLabel)
#removes any part of the OldLabel column that starts with 20 and ends with 2 digits, e.g: 2011 or 2008
有没有办法让 gsub 用后面的 space 替换序列,这样它就可以在它替换的那一年左右摆脱任何 spaces ?我尝试使用 "\b"
作为我的替换文本,但只是用 b
代替了它,而不是后面的 space.
编辑:根据请求,OldLabel
的一个例子是 "Valley Summer 2014"
,它应该变成 "Valley Summer"
,但最终是 "Valley Summer "
我当前的代码。然而,有些也可能是 2012 Valley Summer
的形式,所以我认为简单地在模式中包含 space 是不够稳健的。
试试这个:
data["NewLabel"] <- gsub("[ ]{0,1}20[[:digit:]]{2}[ ]{0,1}", "", data$OldLabel)
成对的花括号是重复量词,其范围由一个(精确)值或两个(最小值和最大值)值确定。有关详细信息,请参阅 ?regex
。 (您不想用退格字符替换它们。)
test <- c("2012 Valley Summer", "Valley Summer 2014")
gsub("[ ]{0,1}20[[:digit:]]{2}[ ]{0,1}", "", test)
#[1] "Valley Summer" "Valley Summer"
data["NewLabel"] <- gsub("\s*[0-9]\s*", "", data$OldLabel)