正则表达式 ex

https://campus.datacamp.com/courses/intermediate-r-practice/utilities?ex=5

这个练习不会做,在这里记录一下答案。

数据:

titanic 数据里面 Name 一列:

[888] "Graham, Miss. Margaret Edith"                                                      
[889] "Johnston, Miss. Catherine Helen \"Carrie\""                                        
[890] "Behr, Mr. Karl Howell"                                                             
[891] "Dooley, Mr. Patrick"

任务:

提取出每个人名中的 title,也就是上面代码中的 “Mr” “Miss” 部分。

# Extract the name column from titanic
pass_names <- titanic$Name

# Create titles
titles <- gsub("^.*, (.*?)\\..*$", "\\1", pass_names)

# Call unique() on titles
unique(titles)

难点——正则表达式

() 括号的作用:可以在 replace 时重复使用。
With , (.*?)\\. we use a similar pattern as before, but the parentheses allow us to re-use whatever is matched inside the parentheses in our replacement.

"\\1"的作用:使用括号中的内容 replace 前面整个字符串。
The "\\1" part tells R to replace the entire string with whatever is matched inside the parentheses.

一个例子,理解 \1 的用法:

gsub("(.*?)\\s(.*?)\\s(.*?)(\\?)$", "\\3 \\1 \\2\\4", "are you ready?")
[1] "ready are you?"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值