本文介绍了提取正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从字符串中提取一个数字.
I'm trying to extract a number from a string.
然后对字符串 "aaa12xxx"
执行类似 [0-9]+
的操作,然后得到 "12"
.
And do something like [0-9]+
on the string "aaa12xxx"
and get "12"
.
我认为它会是这样的:
> grep("[0-9]+", "aaa12xxx", value=TRUE)
[1] "aaa12xxx"
然后我想...
> sub("[0-9]+", "\\1", "aaa12xxx")
[1] "aaaxxx"
但我得到了某种形式的回应:
But I got some form of response doing:
> sub("[0-9]+", "ARGH!", "aaa12xxx")
[1] "aaaARGH!xxx"
我遗漏了一个小细节.
推荐答案
使用新的 stringr 包,该包以一致的语法包装了所有现有的正则表达式,并添加了一些缺失的内容:
Use the new stringr package which wraps all the existing regular expression operates in a consistent syntax and adds a few that are missing:
library(stringr)
str_locate("aaa12xxx", "[0-9]+")
# start end
# [1,] 4 5
str_extract("aaa12xxx", "[0-9]+")
# [1] "12"
这篇关于提取正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!