R从字符串中删除第一个字符

问题描述:

我可以从字符串中删除最后一个字符:

I can remove the last character from a string:

listfruit  <- c("aapplea","bbananab","oranggeo")
gsub('.{1}$', '', listfruit)

但是我在尝试从字符串中删除第一个字符时遇到问题.还有第一个和最后一个字符.如果您提供帮助,我将不胜感激.

But I am having problems trying to remove the first character from a string. And also the first and last character. I would be grateful for your help.

如果我们需要去掉第一个字符,使用sub,匹配一个字符(.代表一个单个字符),将其替换为 ''.

If we need to remove the first character, use sub, match one character (. represents a single character), replace it with ''.

sub('.', '', listfruit)
#[1] "applea"  "bananab" "ranggeo"

或者对于第一个和最后一个字符,匹配字符串开头(^.)或字符串结尾(.$)的字符并替换它带有 ''.

Or for the first and last character, match the character at the start of the string (^.) or the end of the string (.$) and replace it with ''.

gsub('^.|.$', '', listfruit)
#[1] "apple"  "banana" "rangge"

我们也可以将其作为一个组捕获并替换为反向引用.

We can also capture it as a group and replace with the backreference.

sub('^.(.*).$', '\\1', listfruit)
#[1] "apple"  "banana" "rangge"

另一个选项是 substr

substr(listfruit, 2, nchar(listfruit)-1)
#[1] "apple"  "banana" "rangge"