首页 > 解决方案 > 不要在句末包含 gsub 句号

问题描述

我正在尝试在 R 中做一个 gsub 以用箭头替换所有数字(例如:$1.48、1,765、87)。(<>,<<1,765>>,<<87>>)

这是我当前的 gsub:

text<-c("数字示例是一和二、3、1,284 和五十九。", "这个冰棒售价 1.48 美元。")

subbedNum<-gsub("\\b([$0-9.,]+)\\b", "<<\\1>>", text)

然而,它的结果是在句尾的句号周围也放置了箭头,并且箭头中没有 $:

[1]  "My favorite numbers are  <<8>>, <<3,289>> and <<4>><<.>>"
[2]  "This book costs $<<1.48.>>"

预期输出是:

[1,]"My favorite numbers are  <<8>>, <<3,289>> and <<4>>."
[2,]  "This book costs <<$1.48>>."

我怎样才能改变这个?

标签: rregexgsub

解决方案


代替单词边界(可能有一些边缘情况),我们可以捕获任何非数字之后的数字,后跟一个点或逗号,以及一个或多个数字。在替换中,使用捕获组的反向引用并将其格式化为<<>>

gsub("[^$0-9.,]([$0-9]+([.,][0-9]+)?)\\b", "<<\\1>>", text)
#[1] "Examples of numbers are one and two,<<3>>,<<1,284>> and fifty nine."
#[2] "This ice pop costs<<$1.48>>."  

数据

text<-c( "Examples of numbers are one and two, 3, 1,284 and fifty nine.", "This ice pop costs $1.48.") 

推荐阅读