【问题标题】:R separate words from numbers in stringR将单词与字符串中的数字分开
【发布时间】:2019-04-25 19:12:56
【问题描述】:

我需要清理一些包含单词和数字或只有数字的数据字符串。

下面是玩具样品

library(tidyverse)

c("555","Word 123", "two words 123", "three words here 123") %>%  
sub("(\\w+) (\\d*)",  "\\1|\\2", .)

结果是这样的:

[1] "555"                  "Word|123"             "two|words 123"        "three|words here 123"

但我想放置“|”在最后一组数字之前,如下所示

[1] "|555"                  "Word|123"             "two words|123"        "three words here|123"

【问题讨论】:

  • 试试sub("(\\w+ )?(\\d)", "\\1|\\2", v1)
  • @akrun 这行得通,你能把它作为答案让我接受吗?

标签: r regex data-cleaning


【解决方案1】:

我们可以使用 sub 匹配零个或多个空格 (\\s*),后跟我们捕获为一组的数字 ((\\d)),在替换中使用 | 后跟反向引用 (@987654325 @) 被捕获的组

sub("\\s*(\\d)", "|\\1", v1)
#[1] "|555"                 "Word|123"            
#[3] "two words|123"        "three words here|123"

数据

v1 <- c("555","Word 123", "two words 123", "three words here 123")

【讨论】:

    【解决方案2】:

    你可以使用

    ^(.*?)\s*(\d*)$
    

    替换为\1|\2。请参阅regex demo

    在 R 中:

    sub("^(.*?)\\s*(\\d*)$", "\\1|\\2", .)
    

    详情

    • ^ - 字符串开头
    • (.*?) - 捕获组 1:任何 0+ 个字符,尽可能少
    • \s* - 零个或多个空格
    • (\d*) - 捕获组 2:零个或多个数字
    • $ - 字符串结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-26
      • 2018-08-24
      • 2019-10-03
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多