首页 > 解决方案 > 在数字之间拆分字符串

问题描述

与此处上传的问题类似: 拆分字符串和数字 我有一个包含数字和单词的字符串,其模式为:

20.40title1. description1. 21.00title2. description2 ... 

我想要的最终产品的形式是

Hour   title   description
20.40  title1  description1
21.00  title2  description2
 ...    ...       ...

所以我可能需要在每次出现数字之前拆分字符串,然后在第一次出现“。”时再次拆分它。第一步我遇到了一些麻烦。

谢谢,大卫

标签: rstringsplit

解决方案


由于分隔符的宽度为零,因此将其视为提取或匹配任务似乎比拆分任务更容易。对于这种方法,您首先编写正则表达式来匹配您要提取的每个部分。该stringr::str_match功能是一种方便的方法。

x <- "20.40title1. description1. 21.00title2. description2"

out <- do.call(
    cbind,
    str_match_all(
        x,
        c("\\d+\\.\\d+",
          "title\\d+",
          "description\\d+")))

如果需要,您可以清理并命名结果;

out <- setNames(type.convert(as.data.frame(out)),
                c("Hour", "title", "description"))
out
##   Hour  title  description
## 1 20.4 title1 description1
## 2 21.0 title2 description2

推荐阅读