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包介紹學習

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 在挖掘分析的過程當中對字符串的處理是極為重要的,且出現也較為頻繁,R語言作為當前最為流行的開源數據分析和可視化平臺...
    果果哥哥BBQ閱讀 5,944評論 0 8
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 生活中或者工作中,我們可能會遇到各種外界的壓力,一味逃避可能情況更加糟糕,勇敢面對才是硬道理。日本培訓師九世浩司的...
    關鍵期育兒錦囊閱讀 338評論 0 5
  • 蝴蝶效應 “一只南美洲亞馬遜河流域熱帶雨林中的蝴蝶,偶爾扇動幾下翅膀,可以在兩周以后引...
    f961ff2e749a閱讀 694評論 6 0