R语言字符串管家--stringr包案例解析

注,有疑问 加QQ群..[174225475].. 共同探讨进步
有偿求助请 出门左转 door , 合作愉快

str_detect()

detects the presence or absence of a pattern and returns a logical vector (similar to grepl()). str_subset() returns the elements of a character vector that match a regular expression (similar to grep() with value = TRUE)`.

# Which strings contain phone numbers?
str_detect(strings, phone)
#> [1] FALSE  TRUE  TRUE  TRUE

str_subset()

Each pattern matching function has the same first two arguments, a character vector of strings to process and a single pattern to match. stringr provides pattern matching functions to detect, locate, extract, match, replace, and split strings. I’ll illustrate how they work with some strings and a regular expression designed to match (US) phone numbers:

strings <- c(
  "apple", 
  "219 733 8965", 
  "329-293-8753", 
  "Work: 579-499-7527; Home: 543.355.3679"
)
phone <- "([2-9][0-9]{2})[- .]([0-9]{3})[- .]([0-9]{4})"

str_subset(strings, phone)
#> [1] "219 733 8965"                          
#> [2] "329-293-8753"                          
#> [3] "Work: 579-499-7527; Home: 543.355.3679"

str_sub(strings,start=1,end=4)
[1] "appl" "219 " "329-" "Work"

str_extract()

extracts text corresponding to the first match, returning a character vector.
str_extract_all() extracts all matches and returns a list of character vectors.

# What are the phone numbers?
str_extract(strings, phone)
#> [1] NA             "219 733 8965" "329-293-8753" "579-499-7527"
str_extract_all(strings, phone)
#> [[1]]
#> character(0)
#> 
#> [[2]]
#> [1] "219 733 8965"
#> 
#> [[3]]
#> [1] "329-293-8753"
#> 
#> [[4]]
#> [1] "579-499-7527" "543.355.3679"
str_extract_all(strings, phone, simplify = TRUE)
#>      [,1]           [,2]          
#> [1,] ""             ""            
#> [2,] "219 733 8965" ""            
#> [3,] "329-293-8753" ""            
#> [4,] "579-499-7527" "543.355.3679"

str_replace()

replaces the first matched pattern and returns a character vector.
str_replace_all() replaces all matches. Similar to sub() and gsub().

str_replace(strings, phone, "XXX-XXX-XXXX")
#> [1] "apple"                                 
#> [2] "XXX-XXX-XXXX"                          
#> [3] "XXX-XXX-XXXX"                          
#> [4] "Work: XXX-XXX-XXXX; Home: 543.355.3679"
str_replace_all(strings, phone, "XXX-XXX-XXXX")
#> [1] "apple"                                 
#> [2] "XXX-XXX-XXXX"                          
#> [3] "XXX-XXX-XXXX"                          
#> [4] "Work: XXX-XXX-XXXX; Home: XXX-XXX-XXXX"
a1 <- matrix(c('haode','haod2',3,3.1415926,'buhao','haode'),ncol=2)
a1
#     [,1]    [,2]       
#[1,] "haode" "3.1415926"
#[2,] "haod2" "buhao"    
#[3,] "3"     "haode"
matrix(str_replace_all(a1,c('haode'='1','buhao'='2')),ncol=2)
#     [,1]    [,2]       
#[1,] "1"     "3.1415926"
#[2,] "haod2" "2"        
#[3,] "3"     "1" 
str_sub(a1,-3,-1)='nd' # replace fixed position words
a1
#[1] "hand"     "hand"     "nd"       "3.1415nd" "bund"     "hand"    
# --------------------------------
fruits <- c("one apple", "two pears", "three bananas")
str_replace(fruits, "[aeiou]", "-")
#[1] "-ne apple"     "tw- pears"     "thr-e bananas"
str_replace_all(fruits, "[aeiou]", "-")
#[1] "-n- -ppl-"     "tw- p--rs"     "thr-- b-n-n-s"
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
#[1] "1ne apple"     "tw2 pears"     "thr3e bananas"
str_replace_all(fruits, "[aeiou]", c("1", "2", "3"))
#[1] "1n1 1ppl1"     "tw2 p22rs"     "thr33 b3n3n3s"
str_replace_all(fruits, c("a", "e", "i"), "-")
#[1] "one -pple"     "two p-ars"     "three bananas"
str_replace_all(fruits, "[aeiou]", toupper)
#[1] "OnE ApplE"     "twO pEArs"     "thrEE bAnAnAs"
str_replace_all(fruits, "b", NA_character_)
#[1] "one apple" "two pears" NA

str_split()

splits a string into a variable number of pieces and returns a list of character vectors.
str_split_fixed() splits the string into a fixed number of pieces based on a pattern and returns a character matrix.

str_split("a-b-c", "-") # return a list
#> [[1]]
#> [1] "a" "b" "c"
str_split("a-b-c", "-",simplify = TRUE) # return a matrix
#     [,1] [,2] [,3]
#[1,] "a"  "b"  "c" 
str_split_fixed("a-b-c", "-", n = 2) # return a matrix
#>      [,1] [,2] 
#> [1,] "a"  "b-c"

str_c()

功能与base::paste()函数相仿

str_c(letters, collapse = "")
[1] "abcdefghijklmnopqrstuvwxyz"
str_c(letters, collapse = ", ")
[1] "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"
str_c("Letter", head(letters), sep = ": ")
[1] "Letter: a" "Letter: b" "Letter: c" "Letter: d" "Letter: e" "Letter: f"
# Missing inputs give missing outputs
str_c(c("a", NA, "b"), "-d")
[1] "a-d" NA    "b-d"
# Use str_replace_NA to display literal NAs:
str_c(str_replace_na(c("a", NA, "b")), "-d")
[1] "a-d"  "NA-d" "b-d" 

str_count()

counts the number of matches:

# How many phone numbers in each string?
str_count(strings, phone)
#> [1] 0 1 1 2

str_locate()

locates the first position of a pattern and returns a numeric matrix with columns start and end.
str_locate_all() locates all matches, returning a list of numeric matrices. Similar to regexpr() and gregexpr().

# Where in the string is the phone number located?
(loc <- str_locate(strings, phone))
#>      start end
#> [1,]    NA  NA
#> [2,]     1  12
#> [3,]     1  12
#> [4,]     7  18
str_locate_all(strings, phone)
#> [[1]]
#>      start end
#> 
#> [[2]]
#>      start end
#> [1,]     1  12
#> 
#> [[3]]
#>      start end
#> [1,]     1  12
#> 
#> [[4]]
#>      start end
#> [1,]     7  18
#> [2,]    27  38

str_match()

extracts capture groups formed by () from the first match. It returns a character matrix with one column for the complete match and one column for each group. str_match_all() extracts capture groups from all matches and returns a list of character matrices. Similar to regmatches().

# Pull out the three components of the match
str_match(strings, phone)
#>      [,1]           [,2]  [,3]  [,4]  
#> [1,] NA             NA    NA    NA    
#> [2,] "219 733 8965" "219" "733" "8965"
#> [3,] "329-293-8753" "329" "293" "8753"
#> [4,] "579-499-7527" "579" "499" "7527"
str_match_all(strings, phone)
#> [[1]]
#>      [,1] [,2] [,3] [,4]
#> 
#> [[2]]
#>      [,1]           [,2]  [,3]  [,4]  
#> [1,] "219 733 8965" "219" "733" "8965"
#> 
#> [[3]]
#>      [,1]           [,2]  [,3]  [,4]  
#> [1,] "329-293-8753" "329" "293" "8753"
#> 
#> [[4]]
#>      [,1]           [,2]  [,3]  [,4]  
#> [1,] "579-499-7527" "579" "499" "7527"
#> [2,] "543.355.3679" "543" "355" "3679"

str_conv:字符编码转换

函数定义:str_conv(string, encoding)
参数列表:
string: 字符串,字符串向量。
encoding: 编码名。

# 把中文字符字节化
x <- charToRaw('你好');x
[1] c4 e3 ba c3
# 默认win系统字符集为GBK,GB2312为GBK字集,转码正常
str_conv(x, "GBK")
[1] "你好"
str_conv(x, "GB2312")
[1] "你好"
str_conv(x, "UTF-8")
[1] "���"
Warning messages:
1: In stri_conv(string, encoding, "UTF-8") :
  input data \xffffffc4 in current source encoding could not be converted to Unicode
# 把unicode转UTF-8
x1 <- "\u5317\u4eac"
str_conv(x1, "UTF-8")
[1] "北京"

str_to_ 大小写转换

x1 <- 'i like to USE R'
str_to_lower(x1)
[1] "i like to use r"
str_to_upper(x1)
[1] "I LIKE TO USE R"
str_to_title(x1)
[1] "I Like To Use R"

stringr中的正则表达式

注:R语言中正则表达式的不同之处是转义符号是“\”,其他方面和通常的“正则表达式”是一样的

转义字符

\o NUL字符(\u0000)
\t 制表符(\0009)
\n 换行符(\000A)
\v 垂直制表符(\u000B)
\f 换页符(\000C)
\r 回车符(\000D)
\xnn 十六进制拉丁字符
\uxxxx十六进制unicode字符
\cX 控制字符
这些转义字符中比较常用的就是换行符了,其他记不住可以上网查。还有一些字符具有特殊含义,如果需要匹配这些字符的时候需要在前面加上反斜杠进行转义。
^ $ . * + ? = ! : | \ / ( ) [ ] { }

字符类

[...] 方括号内任意字符
[^...] 不在方括号内任意字符
. 除换行符和其他unicode行终止符之外的任意字符
\w 等价于[a-zA-Z0-9]
\W 等价于[^a-zA-Z0-9]
\s 任何unicode空白符
\S 任何非unicode空白符
\d 等价于[0-9]
\D 等价于[^0-9]
[\b] 退格

这个字符类很重要,需要记忆。

重复

{n,m} 匹配前一项至少n次,不超过m次
{n,} 匹配前一项至少n次
{n} 匹配前一项n次
? 等价于{0,1}
\+ 等价于{1,}
\* 等价于{0,}
x? 描述符后跟随一个"?"表示非贪婪匹配:从字符串中第一个可能匹配的位置,尽量少的匹配。如“??”、“{1,5}?”等

选择、分组和引用

“|”与逻辑表达式中的或类似,前后两者任意一个匹配,很好理解。而圆括号用来分组和引用,功能就比较复杂了。
把单独的项组合成子表达式,以便重复、选择等操作。
完整的模式中定义子模式,从而在匹配成功后从目标串中抽出和圆括号中的子模式匹配的部分。
同一个正则表达式中后部引用前部的正则表达式,注意因为子表达式可以嵌套,所以它的位置是参与计数的左括号的位置。如果不创建带数字编码的引用,可以用"(?"和")"表示。
举个简单的例子,如果要匹配单引号或双引号中的字符,可能会写成下面这样:
/['"][^'"]['"]/
但是如果我们是想成对的匹配'abc'而不是匹配'abc"的话需要这么改写:
/(['"])[^'"]
\1/

指定匹配位置的元素称为锚。

^ 匹配字符串开头,多行匹配一行的开头
$ 匹配字符串结尾,多行匹配一行的结尾
\b 匹配一个单词的边界,位于\w和\W之间的位置
\B 匹配非单词边界
(?=p) 要求接下来的字符都与p匹配,但不能包括匹配p的那些字符
(?!p) 要求接下来的字符不与p匹配

修饰符

i 忽略大小写
m 多行匹配模式
g 全局匹配

字符串中的模式匹配

search

查找匹配的字符串,不支持全局匹配,返回第一个子串的起始位置。
"JavaScript".search(/script/i) //4

match

返回由匹配结果组成的数组,默认返回第一个匹配的字符串,如果全局匹配则返回所有匹配字符串。当使用括号分组的时候第一个元素为匹配的字符串,其后为圆括号中各个匹配的子字符串

split

这是将字符串转化为数组的方法。一般用字符串做分隔符匹配,如果使用正则表达式,则在匹配字符串的前后方断开。同时注意以下几点:
匹配到开头内容,返回数组第一个元素为空字符串。
匹配到结尾内容,返回数组最后一个元素为空字符串。
未匹配,返回数组只包含未切分的字符串。

replace
$n 匹配第n个匹配正则表达式中的圆括号子表达式文本  
$& 匹配正则表达式的子串  
$` 匹配子串左边的文本  
$' 匹配子串右边的文本  
$$ 匹配美元符号 
RegExp对象

属性
source 正则表达式文本
global 只读布尔值,是否有修饰符g
ignoreCase 只读布尔值,是否有修饰符i
multiline 只读布尔值,是否有修饰符m
lastIndex 下一次检索开始的位置,用于exec()和test()
方法
exec()
类似String.match,不过不能使用全局匹配。匹配同时修改lastIndex值为紧挨着匹配子串的字符位置,如果未匹配则为0。
test()
返回布尔值,可以修改lastIndex从指定位置开始匹配

参考资料

stringr in cran
stringr包介绍学习

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 在挖掘分析的过程当中对字符串的处理是极为重要的,且出现也较为频繁,R语言作为当前最为流行的开源数据分析和可视化平台...
    果果哥哥BBQ阅读 5,753评论 0 8
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,712评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 生活中或者工作中,我们可能会遇到各种外界的压力,一味逃避可能情况更加糟糕,勇敢面对才是硬道理。日本培训师九世浩司的...
    关键期育儿锦囊阅读 278评论 0 5
  • 蝴蝶效应 “一只南美洲亚马逊河流域热带雨林中的蝴蝶,偶尔扇动几下翅膀,可以在两周以后引...
    f961ff2e749a阅读 653评论 6 0