English · PDF 245
phone <- regex(" \(? # 可选的左括号 (\d{3}) # 区号 [)- ]? # 可选的右括号、连字符或空格 (\d{3}) # 另外三个数字 [ -]? # 可选的空格或连字符 (\d{3}) # 再三个数字 ", comments = TRUE) str_match("514-791-8141", phone) #> [,1] [,2] [,3] [,4] #> [1,] "514-791-814" "514" "791" "814"
除了 regex() 之外,你还可以使用另外三个函数:
microbenchmark::microbenchmark( fixed = str_detect(sentences, fixed("the")), regex = str_detect(sentences, "the"), times = 20 ) #> Unit: microseconds #> expr min lq mean median uq max neval cld #> fixed 116 117 136 120 125 389 20 a #> regex 333 337 346 338 342 467 20 b
在处理非英语数据时要小心使用 fixed()。这之所以有问题,是因为同一个字符往往有多种表示方式。例如,定义 "á" 有两种方式:要么作为单个字符,要么作为 "a" 加上一个重音符号:
a1 <- "\u00e1" a2 <- "a\u0301" c(a1, a2) #> [1] "á" "á"