我正在尝试扩展当前由破折号分隔的数字范围以包含所有数字。
好消息是我找到了有助于以下配置的代码(不是我的):
“宴会厅 1-3”产生“宴会厅 1、宴会厅 2、宴会厅 3”,这就是我想要的。问题是,这是以破折号前后没有空格为条件的。目前,“宴会厅 1 - 3”返回“宴会厅 1 -3、宴会厅 1 - 3、宴会厅 1 - 3”;这不是所需的输出。
请注意,由于多种原因,必须保留破折号前后的空格。 “Ballroom 1 - 3”的输入必须保持不变。
## Dealing with Dash Seperated Sequences of Numbers
expand.dash <- function(dashed) {
limits <- as.numeric(unlist(strsplit(dashed, '-')))
seq(limits[1], limits[2])
}
expand.ballrooms <- function(txt) {
str <- gsub('\\d+-\\d+', '%d', txt)
dashed_str <- gsub('[a-zA-Z ]+', '', txt)
sprintf(str, expand.dash(dashed_str))
}
expand.ballrooms("Ballroom 1-3")
# this works but the line below fails to output the desired result
expand.ballrooms("Ballroom 1 - 3")
# Result should be identical to the the output returned by the previous line.
虽然没有弹出错误消息,但破折号前后的空格会导致输出重复。
In expand.ballrooms
改变这个
gsub('\\d+-\\d+', '%d', txt)
to this:
gsub('\\d+\\s*-\\s*\\d+', '%d', txt)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)