R中的环视正则表达式模式

Lookaround regular expression pattern in R

我坚持创建正确的正则表达式模式,该模式将拆分我的数据框列的内容,而不会让我丢失任何元素。 我必须使用 tidyr 包中的 separate() 函数,因为这是较长处理管道的一部分。由于我不想丢失字符串中的任何元素,因此我正在开发一个 lookahead/lookbehind 表达式。

需要拆分的字符串可以遵循以下模式之一:

我想在每次元素更改时拆分,所以在字母和破折号之后。可以有一个或多个字母,一个或多个数字,但只能有一个破折号。只包含字母的字符串,不需要拆分。

这是我尝试过的:

library(tidyr) 
myDat = data.frame(drugName = c("ab-1234", 'ab-1234', 'ab-1234',
                                'placebo', 'anotherdrug', 'andanother',
                                'xyz123', 'xyz123', 'placebo', 'another',
                                'omega-3', 'omega-3', 'another', 'placebo'))
drugColNames = paste0("X", 1:3) 

# This pattern doesn't split strings that only consist of number and letters, e.g. "xyz123" is not split after the letters.
pat = '(?=-[0-9+])|(?<=[a-z+]-)'

# This pattern splits at all the right places, but the last group (the numbers), is separated and not kept together.
# pat = '(?=-[0-9+]|[0-9+])|(?<=[a-z+]-)'

splitDat = separate(myDat, drugName,
         into = drugColNames,
         sep = pat)

拆分的输出应该是:

"ab-1234" --> "ab" "-" "123"
"xyz123" --> "xyz" "123"
"omega-3" --> "omega" "-" "3"

非常感谢您的帮助。 :)

在这里使用 extract 会更容易,因为我们没有固定的分隔符,这也将避免使用正则表达式环视。

tidyr::extract(myDat, drugName, drugColNames, '([a-z]+)(-)?(\d+)?', remove = FALSE)

#      drugName          X1 X2   X3
#1      ab-1234          ab  - 1234
#2      ab-1234          ab  - 1234
#3      ab-1234          ab  - 1234
#4      placebo     placebo        
#5  anotherdrug anotherdrug        
#6   andanother  andanother        
#7       xyz123         xyz     123
#8       xyz123         xyz     123
#9      placebo     placebo        
#10     another     another        
#11     omega-3       omega  -    3
#12     omega-3       omega  -    3
#13     another     another        
#14     placebo     placebo        

您可以使用

> extract(myDat, "drugName",drugColNames, "^([[:alpha:]]+)(\W*)(\d*)$", remove=FALSE)
      drugName          X1 X2   X3
1      ab-1234          ab  - 1234
2      ab-1234          ab  - 1234
3      ab-1234          ab  - 1234
4      placebo     placebo        
5  anotherdrug anotherdrug        
6   andanother  andanother        
7       xyz123         xyz     123
8       xyz123         xyz     123
9      placebo     placebo        
10     another     another        
11     omega-3       omega  -    3
12     omega-3       omega  -    3
13     another     another        
14     placebo     placebo        
> 

用于提取数据的正则表达式是

^([[:alpha:]]+)(\W*)(\d*)$

参见regex demo

详情

  • ^ - 字符串开头
  • ([[:alpha:]]+) - 第 1 组(第 X1 列):一个或多个字母
  • (\W*) - 第 2 组(第 X2 列):一个或多个非单词字符
  • (\d*) - 第 3 组(第 X3 列):一位或多位数字
  • $ - 字符串结尾。

要删除原始列,请删除 remove=FALSE