注,有疑问 加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从指定位置开始匹配