欢迎

R 中级正则表达式

Angelo Zehr

Data Journalist

你可能停留在这里

R 中级正则表达式

从 Rebus 到自定义表达式

"cat" 是否以 "c" 开头?

Rebus 写法:

str_detect("cat", pattern = START %R% "c")

正则表达式:

str_detect("cat", pattern = "^c")
R 中级正则表达式

前置要求:stringr

str_detect(string, pattern)
str_match(string, pattern)
R 中级正则表达式

正则表达式能帮你做到什么

带高亮的文本块

R 中级正则表达式

正则表达式能帮你做到什么

带高亮的文本块

R 中级正则表达式

我们的第一个数据集

movie_titles <- c(
  "Karate Kid",
  "The Twilight Saga: Eclispe",
  "Knight & Day",
  "Shrek Forever After (3D)",
  "Marmaduke.",
  "Predators",
  "StreetDance (3D)",
  "Robin Hood",
  "Micmacs A Tire-Larigot",
  "Sex And the City 2",
...
movie_titles[
  str_detect(
    movie_titles,
    pattern = "^K"
  )
]
"Karate Kid",
"Knight & Day",
...
R 中级正则表达式

正则中的特殊字符

特殊字符 含义
^ 角号:标记行或字符串的开头
$ 美元符:标记行或字符串的结尾
. 句点:匹配任意字符(字母、数字、空白)
\\. 两个反斜杠:转义句点以匹配实际的点号
R 中级正则表达式

示例

代码 结果
str_match("Book", "^.") 匹配到 "B"
str_match("Book", ".$") 匹配到 "k"
str_match("Book", "\\.") 无匹配
str_match("Book.", "\\.") 匹配到 "."
R 中级正则表达式

开始练习吧!

R 中级正则表达式

Preparing Video For Download...