删除字符串开头和结尾的数字 [英] Remove numbers at the beginning and end of a string
本文介绍了删除字符串开头和结尾的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下向量:
words <- c("5lang","kasverschil2","b2b")
我想删除 "5lang"
中的 "5"
和 "kasverschil2"
中的 "2"
.但我不想删除 "b2b"
中的 "2"
.
I want to remove "5"
in "5lang"
and "2"
in "kasverschil2"
. But I do NOT want to remove "2"
in "b2b"
.
推荐答案
gsub("^\d+|\d+$", "", words)
#[1] "lang" "kasverschil" "b2b"
另一种选择是使用 stringi
library(stringi)
stri_replace_all_regex(words, "^\d+|\d+$", "")
#[1] "lang" "kasverschil" "b2b"
这里使用 OP 提供的数据集的变体是 3 种主要解决方案的基准(请注意,这些字符串非常短且人为;结果可能在更大的真实数据集上有所不同):
Using a variant of the data set provided by the OP here are benchmarks for 3 three main solutions (note that these strings are very short and contrived; results may differ on a larger, real data set):
words <- rep(c("5lang","kasverschil2","b2b"), 100000)
library(stringi)
library(microbenchmark)
GSUB <- function() gsub("^\d+|\d+$", "", words)
STRINGI <- function() stri_replace_all_regex(words, "^\d+|\d+$", "")
GREGEXPR <- function() {
gregexpr(pattern='(^[0-9]+|[0-9]+$)', text = words) -> mm
sapply(regmatches(words, mm, invert=TRUE), paste, collapse="")
}
microbenchmark(
GSUB(),
STRINGI(),
GREGEXPR(),
times=100L
)
## Unit: milliseconds
## expr min lq median uq max neval
## GSUB() 301.0988 349.9952 396.3647 431.6493 632.7568 100
## STRINGI() 465.9099 513.1570 569.1972 629.4176 738.4414 100
## GREGEXPR() 5073.1960 5706.8160 6194.1070 6742.1552 7647.8904 100
这篇关于删除字符串开头和结尾的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文