注嚼摩,有疑問(wèn) 加QQ群..[174225475].. 共同探討進(jìn)步
有償求助請(qǐng) 出門左轉(zhuǎn) 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()函數(shù)相仿
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:字符編碼轉(zhuǎn)換
函數(shù)定義:str_conv(string, encoding)
參數(shù)列表:
string: 字符串拐袜,字符串向量舀奶。
encoding: 編碼名。
# 把中文字符字節(jié)化
x <- charToRaw('你好');x
[1] c4 e3 ba c3
# 默認(rèn)win系統(tǒng)字符集為GBK,GB2312為GBK字集,轉(zhuǎn)碼正常
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轉(zhuǎn)UTF-8
x1 <- "\u5317\u4eac"
str_conv(x1, "UTF-8")
[1] "北京"
str_to_ 大小寫轉(zhuǎn)換
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中的正則表達(dá)式
注:R語(yǔ)言中正則表達(dá)式的不同之處是轉(zhuǎn)義符號(hào)是“\”,其他方面和通常的“正則表達(dá)式”是一樣的
轉(zhuǎn)義字符
\o NUL字符(\u0000)
\t 制表符(\0009)
\n 換行符(\000A)
\v 垂直制表符(\u000B)
\f 換頁(yè)符(\000C)
\r 回車符(\000D)
\xnn 十六進(jìn)制拉丁字符
\uxxxx十六進(jìn)制unicode字符
\cX 控制字符
這些轉(zhuǎn)義字符中比較常用的就是換行符了悲雳,其他記不住可以上網(wǎng)查。還有一些字符具有特殊含義香追,如果需要匹配這些字符的時(shí)候需要在前面加上反斜杠進(jìn)行轉(zhuǎn)義合瓢。
^ $ . * + ? = ! : | \ / ( ) [ ] { }
字符類
[...] 方括號(hào)內(nèi)任意字符
[^...] 不在方括號(hào)內(nèi)任意字符
. 除換行符和其他unicode行終止符之外的任意字符
\w 等價(jià)于[a-zA-Z0-9]
\W 等價(jià)于[^a-zA-Z0-9]
\s 任何unicode空白符
\S 任何非unicode空白符
\d 等價(jià)于[0-9]
\D 等價(jià)于[^0-9]
[\b] 退格
這個(gè)字符類很重要,需要記憶透典。
重復(fù)
{n,m} 匹配前一項(xiàng)至少n次晴楔,不超過(guò)m次
{n,} 匹配前一項(xiàng)至少n次
{n} 匹配前一項(xiàng)n次
? 等價(jià)于{0,1}
\+ 等價(jià)于{1,}
\* 等價(jià)于{0,}
x? 描述符后跟隨一個(gè)"?"表示非貪婪匹配:從字符串中第一個(gè)可能匹配的位置迁央,盡量少的匹配。如“??”滥崩、“{1,5}?”等
選擇岖圈、分組和引用
“|”與邏輯表達(dá)式中的或類似,前后兩者任意一個(gè)匹配钙皮,很好理解蜂科。而圓括號(hào)用來(lái)分組和引用,功能就比較復(fù)雜了短条。
把單獨(dú)的項(xiàng)組合成子表達(dá)式导匣,以便重復(fù)、選擇等操作茸时。
完整的模式中定義子模式贡定,從而在匹配成功后從目標(biāo)串中抽出和圓括號(hào)中的子模式匹配的部分。
同一個(gè)正則表達(dá)式中后部引用前部的正則表達(dá)式可都,注意因?yàn)樽颖磉_(dá)式可以嵌套缓待,所以它的位置是參與計(jì)數(shù)的左括號(hào)的位置。如果不創(chuàng)建帶數(shù)字編碼的引用渠牲,可以用"(?"和")"表示旋炒。
舉個(gè)簡(jiǎn)單的例子,如果要匹配單引號(hào)或雙引號(hào)中的字符签杈,可能會(huì)寫成下面這樣:
/['"][^'"]['"]/
但是如果我們是想成對(duì)的匹配'abc'而不是匹配'abc"的話需要這么改寫:
/(['"])[^'"]\1/
錨
指定匹配位置的元素稱為錨瘫镇。
^ 匹配字符串開頭,多行匹配一行的開頭
$ 匹配字符串結(jié)尾答姥,多行匹配一行的結(jié)尾
\b 匹配一個(gè)單詞的邊界铣除,位于\w和\W之間的位置
\B 匹配非單詞邊界
(?=p) 要求接下來(lái)的字符都與p匹配,但不能包括匹配p的那些字符
(?!p) 要求接下來(lái)的字符不與p匹配
修飾符
i 忽略大小寫
m 多行匹配模式
g 全局匹配
字符串中的模式匹配
search
查找匹配的字符串鹦付,不支持全局匹配尚粘,返回第一個(gè)子串的起始位置。
"JavaScript".search(/script/i) //4
match
返回由匹配結(jié)果組成的數(shù)組睁壁,默認(rèn)返回第一個(gè)匹配的字符串背苦,如果全局匹配則返回所有匹配字符串互捌。當(dāng)使用括號(hào)分組的時(shí)候第一個(gè)元素為匹配的字符串潘明,其后為圓括號(hào)中各個(gè)匹配的子字符串
split
這是將字符串轉(zhuǎn)化為數(shù)組的方法。一般用字符串做分隔符匹配秕噪,如果使用正則表達(dá)式钳降,則在匹配字符串的前后方斷開。同時(shí)注意以下幾點(diǎn):
匹配到開頭內(nèi)容腌巾,返回?cái)?shù)組第一個(gè)元素為空字符串遂填。
匹配到結(jié)尾內(nèi)容誊爹,返回?cái)?shù)組最后一個(gè)元素為空字符串瑰枫。
未匹配,返回?cái)?shù)組只包含未切分的字符串。
replace
$n 匹配第n個(gè)匹配正則表達(dá)式中的圓括號(hào)子表達(dá)式文本
$& 匹配正則表達(dá)式的子串
$` 匹配子串左邊的文本
$' 匹配子串右邊的文本
$$ 匹配美元符號(hào)
RegExp對(duì)象
屬性
source 正則表達(dá)式文本
global 只讀布爾值而克,是否有修飾符g
ignoreCase 只讀布爾值,是否有修飾符i
multiline 只讀布爾值庄萎,是否有修飾符m
lastIndex 下一次檢索開始的位置驳棱,用于exec()和test()
方法
exec()
類似String.match,不過(guò)不能使用全局匹配哆窿。匹配同時(shí)修改lastIndex值為緊挨著匹配子串的字符位置链烈,如果未匹配則為0。
test()
返回布爾值挚躯,可以修改lastIndex從指定位置開始匹配