【问题标题】:remove the numbers from a string, except if there is a letter before从字符串中删除数字,除非前面有一个字母
【发布时间】:2018-01-12 03:19:31
【问题描述】:

我有这个字符串:

     str <-c ("Street 21, h0use blu3 number 23A", "th3 hosp1tal on 7A Street with 12A")
str <- gsub ("\\ b (?! Street) \\ s [0-9] | [0-9]", "", str, perl = T)

这个结果:

"Street, huse blu numberA" "the hosptal onA Street withA"

我正在尝试消除所有数字,除了它们表示街道时,我想要的结果如下:

"Street 21, huse blu number 23A" "th hosptal on 7A Street 12A"

【问题讨论】:

  • 在您的预期输出中 "th hosptal on 7A Street 12A" 单词 with 已被删除。这是故意的吗?如果是,背后的逻辑是什么?
  • 对不起,这完全是一个印刷错误
  • 只是一个注释。 str 是 R 中的一个函数。您可能希望避免以这种方式命名对象。
  • 谢谢,如果想在街道词之前省略删除数字的情况下,是否只修改括号内的内容?也就是这样的结果:`“Street 21, huse blu number A”“A Street with A 的医院”`
  • @MaxTC 回答会使已经给出的答案无效。你可能想问一个新问题。 Stack Overflow 不是技术博客。

标签: r regex


【解决方案1】:

使用lookbehind检查数字前面是否有字母:

str<-c("Street 21, h0use blu3 number 23A", "th3 hosp1tal on 7A Street with 12A")
gsub("(?<=[A-Za-z])\\d+", "", str, perl=TRUE)

[1] "Street 21, huse blu number 23A"   "th hosptal on 7A Street with 12A"

Demo

【讨论】:

  • 在预期结果中,with 不包含在第二项中。
  • @jazzurro OP 的描述没有提到删除 with 这个词。我认为这只是一个错字。
  • 我也是这么想的。我想我们需要请 OP 澄清这一点。
  • 这似乎是一个错字。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
相关资源
最近更新 更多