繁体   English   中英

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

[英]Lookaround regular expression pattern in R

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

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

  • 只有字母(例如'abcd')
  • 字母-破折号-数字(例如'abcd-123')
  • 字母数字(例如'abcd1234')
    列内容应最多分为 3 列,每组一列。

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

这是我尝试过的:

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*)$

请参阅正则表达式演示

细节

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM