在 R 中评估正则表达式



我有一个与正则表达式相关的问题;这是一个代码片段:

rr <- regex("^chapter [\divxlc]", ignore_case = T)
library(dplyr)
dd <- c("hello there", "Chapter 1", "begining of life", "end of chapter", "Chapter X", "Chapter T", "Chapter 10")
dd_df <- data_frame(line=1:length(dd), text = dd)
# dd_df now looks as follows
# A tibble: 7 x 2
  line text            
 <int> <chr>          
1     1 hello there    
2     2 Chapter 1      
3     3 begining of life
4     4 end of chapter  
5     5 Chapter X      
6     6 Chapter T      
7     7 Chapter 10 (edited)

当我根据 dd_df 中的行评估正则表达式时

dd_df %>% mutate(rr = str_detect(text, rr), regexp = "^chapter [\divxlc]")

我得到:

# A tibble: 7 x 4

line text             rr    regexp              
 <int> <chr>            <lgl> <chr>                
1     1 hello there      FALSE "^chapter [\divxlc]"
2     2 Chapter 1        TRUE  "^chapter [\divxlc]"
3     3 begining of life FALSE "^chapter [\divxlc]"
4     4 end of chapter   FALSE "^chapter [\divxlc]"
5     5 Chapter X        TRUE  "^chapter [\divxlc]"
6     6 Chapter T        FALSE "^chapter [\divxlc]"
7     7 Chapter 10       TRUE  "^chapter [\divxlc]"

我无法弄清楚第 2 行和第 7 行如何评估TRUE

您的regex定义为: regex("^chapter [\divxlc]", ignore_case = T)

请注意,ignore_case = T.因此,"^chapter "将与第 2 行和第 7 行中的Chapter匹配。

下一部分是[\divxlc]——这意味着寻找一个digit(\d(或来自ivxlc的角色。

同样在第 2 行和第 7 行中Chapter后跟与d匹配的1。因此这两行(2 & 7(和5是匹配的。

其他行都不符合这两个条件。

最新更新