Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

regex - conditionally remove leading or trailing `.` character in 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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use regular expressions:

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...