用字符串中的单个数字替换数字范围 [英] replace range of numbers with single numbers in a character string

查看:211
本文介绍了用字符串中的单个数字替换数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以用字符串中的单个数字替换数字范围?数字范围可以是n-n,最可能是1-15,也可以是4-10.

Is there any way to replace range of numbers wih single numbers in a character string? Number can range from n-n, most probably around 1-15, 4-10 ist also possible.

可以用a)表示范围-

a <- "I would like to buy 1-3 cats"

或带有单词b),例如:to,bis,jusqu'à

or with a word b) for example: to, bis, jusqu'à

b <- "I would like to buy 1 jusqu'à 3 cats"

结果应该看起来像

"I would like to buy 1,2,3 cats"

我发现了这一点:用某些数字替换数字范围但不能真正在R中使用它.

I found this: Replace range of numbers with certain number but could not really use it in R.

推荐答案

gsubfn类似于gsub,但不是用替换字符串替换匹配项,而是允许用户指定一个函数(可能在公式符号).然后,它将匹配项传递给正则表达式中的捕获组,即,将匹配项传递给正则表达式中带括号的部分,作为单独的参数,并将整个匹配项替换为函数的输出.因此,我们匹配"(\\d+)(-| to | bis | jusqu'à )(\\d+)",这将导致三个捕获组,因此该函数需要3个参数.在函数中,我们将seq与其中的第一个和第三个一起使用.请注意,seq可以接受字符参数并将其解释为数字,因此我们不必将参数转换为数字.

gsubfn in the gsubfn package is like gsub but instead of replacing the match with a replacement string it allows the user to specify a function (possibly in formula notation as done here). It then passes the matches to the capture groups in the regular expression, i.e. the matches to the parenthesized parts of the regular expression, as separate arguments and replaces the entire match with the output of the function. Thus we match "(\\d+)(-| to | bis | jusqu'à )(\\d+)" which results in three capture groups so 3 arguments to the function. In the function we use seq with the first and third of these. Note that seq can take character arguments and interpret them as numeric so we did not have to convert the arguments to numeric.

因此,我们得到了这种单线:

Thus we get this one-liner:

library(gsubfn)
s <- c(a, b) # test input strings

gsubfn("(\\d+)(-| to | bis | jusqu'à )(\\d+)", ~ paste(seq(..1, ..3), collapse = ","), s)

给予:

[1] "I would like to buy 1,2,3 cats" "I would like to buy 1,2,3 cats"

这篇关于用字符串中的单个数字替换数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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