【问题标题】:Don't include in gsub period at the end of a sentence不要在句末包含 gsub 句号
【发布时间】:2020-03-25 01:11:17
【问题描述】:

我正在尝试在 R 中使用 gsub 来用箭头周围的箭头替换所有数字(例如:$1.48、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>>."

我该如何改变这个?

【问题讨论】:

    标签: r regex gsub


    【解决方案1】:

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

    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.") 
    

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 2019-04-18
      • 2012-12-25
      相关资源
      最近更新 更多