R使用tidyr :: separate在最后的空白字符处拆分字符串

时间:2015-08-20 13:43:32

标签: regex r dplyr tidyr

假设我有一个这样的数据框:

df<-data.frame(a=c("AA","BB"),b=c("short string","this is the longer string"))

我想根据最后出现的空间使用正则表达式拆分每个字符串。 我试过了:

library(dplyr)
library(tidyr)
df%>%
  separate(b,c("partA","partB"),sep=" [^ ]*$")

但这省略了输出中字符串的第二部分。我想要的输出看起来像这样:

   a              partA  partB
1 AA              short string
2 BB this is the longer string

我该怎么做如果我可以使用tidyr和dplyr,那会很好。

2 个答案:

答案 0 :(得分:16)

我们可以使用捕获组(extract)从tidyr使用(...)。我们匹配零个或多个字符(.*)并将其放在括号((.*))中,然后是零个或多个空格(\\s+),然后是下一个仅包含的捕获组在字符串结尾([^ ])之前不是空格($)的字符。

library(tidyr)
extract(df, b, into = c('partA', 'partB'), '(.*)\\s+([^ ]+)$')
#   a              partA  partB
#1 AA              short string
#2 BB this is the longer string

答案 1 :(得分:0)

您可以将正则表达式的[^ ]*$部分转换为(?=[^ ]*$)非使用模式,positive lookahead(不会在字符串末尾使用非空白字符) ,即它们不会放入匹配值中,因此将保留在输出中):

df%>%
  separate(b,c("partA","partB"),sep=" (?=[^ ]*$)")

或者,由于它与任何空白字符匹配,因此更具通用性:

df %>%
  separate(b,c("partA","partB"),sep="\\s+(?=\\S*$)")

请参见下面的regex demo及其图形:

enter image description here

输出:

   a              partA  partB
1 AA              short string
2 BB this is the longer string