有条件地删除 R 中的前导或尾随 `.` 字符 [英] conditionally remove leading or trailing `.` character in R

查看:41
本文介绍了有条件地删除 R 中的前导或尾随 `.` 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称向量,其中一些名称具有前导和尾随 . 字符,而有些则没有.下面是一个例子:

I have a vector of names where some names have leading and trailing . characters, and some do not. Here is an example:

test <- c('.name.1.','name.2','.name.3.')

我想有条件地删除这些名称中的前导和尾随 . 字符,以返回

I would like to conditionally remove leading and trailing . characters in these names, to return

c('name.1','name.2','name.3')

推荐答案

使用正则表达式:

test <- c('.name.1.','name.2','.name.3.')
gsub('^\\.|\\.$', '', test)
# [1] "name.1" "name.2" "name.3"

正则表达式中的两个反斜杠 \\ 转义了点 .,它实际上表示任何字符.插入符号 ^ 标记字符串的开头,美元,$,标记字符串的结尾.管道 | 是一个逻辑或".所以本质上正则表达式匹配字符串开头的一个点或字符串末尾的一个点,并用一个空字符串替换它.

The two backslashes, \\, in the regular expression escape the dot, ., which would actually mean any character. The caret, ^, marks the beginning of the string, the dollar, $, the end of the string. The pipe, |, is a logical "or". So in essence the regular expression matches a dot at the beginning of the string or a dot at the end of the string and replaces it with an empty string.

有关正则表达式的更多信息,请参见 此处以及有关 gsub 和相关功能的信息 此处.

More information on regular expressions can be found here and information on gsub and related functions here.

这篇关于有条件地删除 R 中的前导或尾随 `.` 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆