我正在尝试在R中执行gsub,以所有数字(例如:$ 1.48、1,765、87)替换为周围的箭头。 (<>,<< 1,765 >>,<< 87 >>)
这是我当前的gsub:
text
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>>."
我该如何更改?
而不是单词边界(可能会有一些边缘情况),我们可以捕获任何非数字之后的数字,然后是点或逗号以及一个或多个数字。在替换中,使用捕获的组的后向引用,并使用<<>>
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.")