1. stringr介紹
stringr包被定義為一致的、簡單易用的字符串工具集。所有的函數和參數定義都具有一致性,比如,用相同的方法進行NA處理和0長度的向量處理。
字符串處理雖然不是R語言中最主要的功能,卻也是必不可少的,數據清洗、可視化等的操作都會用到。對於R語言本身的base包提供的字符串基礎函數,隨着時間的積累,已經變得很多地方不一致,不規范的命名,不標准的參數定義,很難看一眼就上手使用。字符串處理在其他語言中都是非常方便的事情,R語言在這方面確實落后了。stringr包就是為了解決這個問題,讓字符串處理變得簡單易用,提供友好的字符串操作接口。
stringr的項目主頁:https://cran.r-project.org/web/packages/stringr/index.html
2. stringr的API介紹
stringr包1.0.0版本,一共提供了30個函數,方便我們對字符串處理。常用的字符串的處理以str_開頭來命名,方便更直觀理解函數的定義。我們可以根據使用習慣對函數進行分類:
字符串拼接函數
- str_c: 字符串拼接。
- str_join: 字符串拼接,同str_c。
- str_trim: 去掉字符串的空格和TAB(\t)
- str_pad: 補充字符串的長度
- str_dup: 復制字符串
- str_wrap: 控制字符串輸出格式
- str_sub: 截取字符串
- str_sub<- 截取字符串,並賦值,同str_sub
字符串計算函數
- str_count: 字符串計數
- str_length: 字符串長度
- str_sort: 字符串值排序
- str_order: 字符串索引排序,規則同str_sort
字符串匹配函數
- str_split: 字符串分割
- str_split_fixed: 字符串分割,同str_split
- str_subset: 返回匹配的字符串
- word: 從文本中提取單詞
- str_detect: 檢查匹配字符串的字符
- str_match: 從字符串中提取匹配組。
- str_match_all: 從字符串中提取匹配組,同str_match
- str_replace: 字符串替換
- str_replace_all: 字符串替換,同str_replace
- str_replace_na:把NA替換為NA字符串
- str_locate: 找到匹配的字符串的位置。
- str_locate_all: 找到匹配的字符串的位置,同str_locate
- str_extract: 從字符串中提取匹配字符
- str_extract_all: 從字符串中提取匹配字符,同str_extract
字符串變換函數
- str_conv: 字符編碼轉換
- str_to_upper: 字符串轉成大寫
- str_to_lower: 字符串轉成小寫,規則同str_to_upper
- str_to_title: 字符串轉成首字母大寫,規則同str_to_upper
參數控制函數,僅用於構造功能的參數,不能獨立使用。
- boundary: 定義使用邊界
- coll: 定義字符串標准排序規則。
- fixed: 定義用於匹配的字符,包括正則表達式中的轉義符
- regex: 定義正則表達式
stringr
包中的重要函數
函數 | 功能說明 | R Base中對應函數 |
---|---|---|
使用正則表達式的函數 | ||
str_extract() |
提取首個匹配模式的字符 | regmatches() |
str_extract_all() |
提取所有匹配模式的字符 | regmatches() |
str_locate() |
返回首個匹配模式的字符的位置 | regexpr() |
str_locate_all() |
返回所有匹配模式的字符的位置 | gregexpr() |
str_replace() |
替換首個匹配模式 | sub() |
str_replace_all() |
替換所有匹配模式 | gsub() |
str_split() |
按照模式分割字符串 | strsplit() |
str_split_fixed() |
按照模式將字符串分割成指定個數 | - |
str_detect() |
檢測字符是否存在某些指定模式 | grepl() |
str_count() |
返回指定模式出現的次數 | - |
其他重要函數 | ||
str_sub() |
提取指定位置的字符 | regmatches() |
str_dup() |
丟棄指定位置的字符 | - |
str_length() |
返回字符的長度 | nchar() |
str_pad() |
填補字符 | - |
str_trim() |
丟棄填充,如去掉字符前后的空格 | - |
str_c() |
連接字符 | paste(),paste0() |
3.1 字符串拼接函數
3.1.1 str_c,字符串拼接操作,與str_join完全相同,與paste()行為不完全一致。
函數定義:
str_c(..., sep = "", collapse = NULL)
str_join(..., sep = "", collapse = NULL)
參數列表:
…: 多參數的輸入
sep: 把多個字符串拼接為一個大的字符串,用於字符串的分割符。
collapse: 把多個向量參數拼接為一個大的字符串,用於字符串的分割符。
str_c(c('a','a1'),c('b','b1'),sep='-')
str_c(letters[1:5], " is for", "...")
str_c('a','b',sep='-')#sep可設置連接符
str_c('a','b',collapse = "-") # collapse參數,對多個字符串無效
str_c(c('a','a1'),c('b','b1'),collapse='-')
str_c(head(letters), collapse = "") #把多個向量參數拼接為一個大的字符串
str_c(head(letters), collapse = ", ")
str_c(letters[-26], " comes before ", letters[-1])
str_c(letters)
############
#對比str_c()函數和paste()函數之間的不同點。
############
str_c('a','b') #把多個字符串拼接為一個大的字符串。
paste('a','b') # 多字符串拼接,默認的sep參數行為不一致
# 向量拼接字符串,collapse參數的行為一致
str_c(letters, collapse = "") #collapse 將一個向量的所有元素連接成一個字符串,collapse設置元素間的連接符
paste(letters, collapse = "")
#拼接有NA值的字符串向量,對NA的處理行為不一致
str_c(c("a", NA, "b"), "-d") #若為空,則無法連接
paste(c("a", NA, "b"), "-d") #即使空,也可連接
str_c(str_replace_na(c("a", NA, "b")), "-d") #即使空,也可連接
3.1.2 str_trim:去掉字符串的空格和TAB(\t)
函數定義:str_trim(string, side = c("both", "left", "right"))
參數列表:
string: 字符串,字符串向量。
side: 過濾方式,both兩邊都過濾,left左邊過濾,right右邊過濾
去掉字符串的空格和TAB(\t)
str_trim(string, side = c(“both”, “left”, “right”))
string:需要處理的字符串
side:指定剔除空格的位置,both表示剔除首尾兩端空格,left表示剔除字符串首部空格,right表示剔除字符串末尾空格
string <- ‘ Why is me? I have worded hardly! ‘
str_trim(string, side = ‘left’)
str_trim(string, side = ‘right’)
str_trim(string, side = ‘both’)
3.1.3 str_pad:補充字符串的長度
函數定義:str_pad(string, width, side = c("left", "right", "both"), pad = " ")
參數列表:
string: 字符串,字符串向量。
width: 字符串填充后的長度
side: 填充方向,both兩邊都填充,left左邊填充,right右邊填充
pad: 用於填充的字符
> string<-'ning xiao li'
> str_pad(string,10)
[1] "ning xiao li"
> str_pad(string,20)
[1] " ning xiao li"
> str_pad(string,20,side = 'both',pad = '*')
[1] "****ning xiao li****"
> string<-'ning xiao li'
> str_pad(string,10) ##注若指定的長度少於string長度時,將只返回原string
[1] "ning xiao li"
> str_pad(string,20) ## 從右邊補充空格,直到字符串長度為20
[1] " ning xiao li"
> str_pad(string,20,side = 'left',pad = '*') # # 從左邊補充空格,直到字符串長度為20
[1] "********ning xiao li"
> str_pad(string,20,side = 'left',pad = '*') # # 從右邊補充空格,直到字符串長度為20
[1] "********ning xiao li"
> str_pad(string,20,side = 'both',pad = '*') # 從左右兩邊各補充x字符,直到字符串長度為20
[1] "****ning xiao li****"
3.1.4 str_dup: 復制字符串
函數定義:str_dup(string, times)
參數列表:
string:需要重復處理的字符串
times:指定重復的次數
復制一個字符串向量。
> val <- c("abca4", 123, "cba2")
# 復制2次
> str_dup(val, 2)
# 按位置復制
> str_dup(val, 1:3)
3.1.5 str_wrap,控制字符串輸出格式
函數定義:str_wrap(string, width = 80, indent = 0, exdent = 0)
參數列表:
- string: 字符串,字符串向量。
- width: 設置一行所占的寬度。
- indent: 段落首行的縮進值
- exdent: 設置第二行后每行縮進
thanks_path <- file.path(R.home("doc"), "THANKS")
thanks <- str_c(readLines(thanks_path), collapse = "\n")
thanks <- word(thanks, 1, 3, fixed("\n\n"))
cat(str_wrap(thanks), "\n")
cat(str_wrap(thanks, width = 70), "\n") # 設置寬度為70個字符
cat(str_wrap(thanks, width = 80, indent = 6, indent = 2), "\n") # 設置寬度為80字符,首行縮進2字符
cat(str_wrap(thanks, width = 80, indent = 6, exdent = 2), "\n") # 設置寬度為80字符,非首行縮進2字符
3.1.6 str_sub,截取字符串
函數定義:str_sub(string, start = 1L, end = -1L)
參數列表:
- string: 字符串,字符串向量。
- start : 開始位置
- end : 結束位置
str_sub(string, start = 1L, end = -1L) 提取子字符串
str_sub(string, start = 1L, end = -1L) <- value 替換子字符串
截取字符串。
txt <- "I am a little bird"
str_sub(txt, 1, 4) # 截取1-4的索引位置的字符串
str_sub(txt, end=6) # 截取1-6的索引位置的字符串
str_sub(txt, 6) # 截取6到結束的索引位置的字符串
str_sub(txt, c(1, 4), c(6, 8)) # 分2段截取字符串
str_sub(txt, -3) # 通過負坐標截取字符串
str_sub(txt, end = -3)
x <- "AAABBBCCC" #對截取的字符串進行賦值。
str_sub(x, 1, 1) <- 1; x ## 在字符串的1的位置賦值為1
str_sub(x, 2, -2) <- "2345"; x ## 在字符串從2到-2的位置賦值為2345
3.2 字符串計算函數
3.2.1 str_count, 字符串計數
函數定義:str_count(string, pattern = "")
參數列表:
- string: 字符串,字符串向量。
- pattern: 匹配的字符。
# Word boundaries 單詞邊界
words <- c("These are some words.")
str_count(words) #統計語句中單詞的個數
[1] 21
str_count(words, boundary("word"))
str_split(words, " ")[[1]] #將語句分割成單個詞組,最后一個單詞帶有標點
str_split(words, boundary("word"))[[1]]#最后一個單詞不帶有標點
string<-c('ning xiao li','zhang san','zhao guo nan')
str_count(string,'i')
3.2.2 str_length,字符串長度
函數定義:str_length(string)
參數列表:
string: 字符串,字符串向量。
計算字符串的長度:
> str_length(c("I", "am", "寧小麗", NA))
[1] 1 2 3 NA
str_length(),字符長度函數,該函數類似於nchar()函數,但前者將NA返回為NA,而nchar則返回2
3.2.3 str_sort, 字符串值排序,同str_order索引排序
函數定義:
str_sort(x, decreasing = FALSE, na_last = TRUE, locale = "", ...)
str_order(x, decreasing = FALSE, na_last = TRUE, locale = "", ...)
str_order和str_sort的區別在於前者返回排序后的索引(下標),后者返回排序后的實際值
參數列表:
x: 字符串,字符串向量。
decreasing: 排序方向。
na_last:NA值的存放位置,一共3個值,TRUE放到最后,FALSE放到最前,NA過濾處理
locale:按哪種語言習慣排序
#str_sort, 字符串值排序,同str_order索引排序
str_order(c('wo','love','five','stars','red','flag'),locale = "en")
str_sort(c('wo','love','five','stars','red','flag'),locale = "en") # 按ASCII字母排序
str_sort(c('wo','love','five','stars','red','flag'),,decreasing=TRUE) # 倒序排序
str_sort(c('我','愛','五','星','紅','旗'),locale = "zh") # 按拼音排序
對NA值的排序處理
#把NA放最后面 > str_sort(c(NA,'1',NA),na_last=TRUE) [1] "1" NA NA #把NA放最前面 > str_sort(c(NA,'1',NA),na_last=FALSE) [1] NA NA "1" #去掉NA值 > str_sort(c(NA,'1',NA),na_last=NA) [1] "1"
3.3 字符串匹配函數
3.3.1 str_split,字符串分割,同str_split_fixed
函數定義:
str_split(string, pattern, n = Inf)
str_split_fixed(string, pattern, n)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配的字符。
n: 分割個數 #最后一組就不會被分割
對字符串進行分割。
### str_split與str_split_fixed的區別
### 在於前者返回列表格式,后者返回矩陣格式
val <- "abc,123,234,iuuu"
s1<-str_split(val, ","); s1 # 以,進行分割
s2<-str_split(val, ",",2); s2 # 以,進行分割,保留2塊
class(s1) # 查看str_split()函數操作的結果類型list
s3<-str_split_fixed(val, ",",2); s3 # 用str_split_fixed()函數分割,結果類型是matrix
class(s3)
3.3.2 str_subset:返回的匹配字符串
函數定義:
str_subset(string, pattern)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配的字符。
fruit <- c("apple", "banana", "pear", "pinapple")
str_subset(fruit, "a") ## 全文匹配
str_subset(fruit, "ap") ##返回含字符'ap'的單詞
str_subset(fruit, "^a") ## 開頭匹配
str_subset(fruit, "a$") ## 結尾匹配
str_subset(fruit, "b") ##返回含字符'b'的單詞
str_subset(fruit, "[aeiou]") ##返回含'aeiou'任一個字符的單詞
str_subset(c("a", NA, "b"), ".") #丟棄空值
#該函數與word()函數的區別在於前者提取字符串的子串,后者提取的是單詞,而且str_sub也可以其替換的作用。
string <- 'My name is ABDATA, I’m 27.'
str_sub(string, -3,-2) <- 25; string
str_subset()函數與word()函數的區別在於前者提取字符串的子串,后者提取的是單詞,而且str_sub也可以其替換的作用。
3.3.3 word, 從文本中提取單詞(適用於英語環境下的使用)
函數定義:word(string, start = 1L, end = start, sep = fixed(" "))
參數列表:
- string: 字符串,字符串向量。
- start: 開始位置。
- end: 結束位置。
- sep: 匹配字符。
sentences <- c("nxl saw a cat", "nxl sat down")
word(sentences, 1) #提取第一個單詞
word(sentences, 2) #提取第二個單詞
word(sentences, -1) #提取句子的最后一個單詞
word(sentences, 2, -1) #提取第二個單詞到最后一個單詞
word(sentences[1], 1:3, -1) #整個句子從第一個單詞遞減掉三個單詞
word(sentences[1], 1:6, -1) #整個句子從第一個單詞遞減掉的單詞
word(sentences[1], 1, 1:4) #從句子的第一個單詞遞增到第四個單詞
str <- 'abc.def..123.4568.999'
word(str, 1, sep = fixed('..')) # 指定分隔符
word(str, 2, sep = fixed('..'))
word(str, 3, sep = fixed('..'))
val<-'111,222,333,444'
word(val, 1, sep = fixed(',')) # 以,分割,取第一個位置的字符串
word(val, 3, sep = fixed(','))
3.3.4 str_detect匹配字符串的字符-- 檢測函數,用於檢測字符串中是否存在某種匹配模式
函數定義:str_detect(string, pattern)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
> val <- c("abca4", 123, "cba2")
# 檢查字符串向量,是否包括a
> str_detect(val, "a")
# 檢查字符串向量,是否以a為開頭
> str_detect(val, "^a")
# 檢查字符串向量,是否以a為結尾
> str_detect(val, "a$")
3.3.6 str_match,從字符串中提取匹配組
函數定義:
str_match(string, pattern)
str_match_all(string, pattern)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
val <- c("abc", 123, "cba") # 從字符串中提取匹配組
str_match(val, "a") # 匹配字符a,並返回對應的字符
str_match(val, "[0-9]") # 匹配字符0-9,限1個,並返回對應的字符
str_match(val, "[0-9]*") # 匹配字符0-9,不限數量,並返回對應的字符
str_match_all(val, "a") #從字符串中提取匹配組,以字符串matrix格式返回
str_match_all(val, "[0-9]")
str_match()和str_match_all()區別在於前者只提取一次滿足條件的匹配對象,而后者可以提取所有匹配對象
3.3.7 str_replace,字符串替換
函數定義:str_replace(string, pattern, replacement)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
replacement: 用於替換的字符。
val <- c("abc", 123, "cba")
str_replace(val, "[ab]", "-") #替換第一個匹配的字符# 把目標字符串第一個出現的a或b,替換為-
str_replace_all(val, "[ab]", "-") #替換所有匹配的字符 # 把目標字符串所有出現的a或b,替換為-
str_replace_all(val, "[a]", "\1\1") # 把目標字符串所有出現的a,替換為被轉義的字符
str_replace與str_replace_all的區別在於前者只替換一次匹配的對象,而后者可以替換所有匹配的對象
3.3.8 str_replace_na把NA替換為NA字符串
函數定義:str_replace_na(string, replacement = "NA")
參數列表:
- string: 字符串,字符串向量。
- replacement : 用於替換的字符。
把NA替換為字符串
> str_replace_na(c(NA,'NA',"abc"),'x') [1] "x" "NA" "abc"
3.3.9 str_locate,找到的模式在字符串中的位置。
str_locate()和str_locate_all()的區別在於前者只匹配首次,而后者可以匹配所有可能的值
> str_locate(val, "a")
start end
[1,] 1 1
[2,] NA NA
[3,] 3 3
# 用向量匹配
> str_locate(val, c("a", 12, "b"))
start end
[1,] 1 1
[2,] 1 2
[3,] 2 2
# 以字符串matrix格式返回
> str_locate_all(val, "a")
[[1]]
start end
[1,] 1 1
[2,] 4 4
[[2]]
start end
[[3]]
start end
[1,] 3 3
# 匹配a或b字符,以字符串matrix格式返回
> str_locate_all(val, "[ab]")
[[1]]
start end
[1,] 1 1
[2,] 2 2
[3,] 4 4
[[2]]
start end
[[3]]
start end
[1,] 2 2
[2,] 3 3
string <- c('nxl123','zhazha234')
str_locate(string,'z')
str_locate(string,'n')
str_locate_all(string,'n')
3.3.10 str_extract從字符串中提取匹配模式
函數定義:
str_extract(string, pattern)
str_extract_all(string, pattern, simplify = FALSE)
參數列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
simplify: 返回值,TRUE返回matrix,FALSE返回字符串向量
shopping_list <- c("apples 4x4", "bag of flour", "bag of sugar", "milk x2")
str_extract(shopping_list, "\\d") # 提取數字 #提取匹配模式的第一個字符串
str_extract(shopping_list, "[a-z]+") #提取字母
str_extract_all(shopping_list, "[a-z]+") # 提取所有匹配模式的字母,結果返回一個列表
str_extract_all(shopping_list, "\\d") # 提取所有匹配模式的數字
# 提取所有匹配模式的字符串,結果返回一個矩陣,通過simplify = TRUE設置
str_extract_all(shopping_list, "\\b[a-z]+\\b", simplify = TRUE)
str_extract_all(shopping_list, "\\d", simplify = TRUE)
str_extract(string, pattern) 提取匹配的第一個字符串
str_extract_all(string, pattern, simplify = FALSE) 提取匹配的所有字符串
功能與str_match(),str_match_all()函數類似
3.4 字符串變換函數
3.4.1 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] "你好" # 轉UTF-8失敗 > 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 2: In stri_conv(string, encoding, "UTF-8") : input data \xffffffe3\xffffffba in current source encoding could not be converted to Unicode 3: In stri_conv(string, encoding, "UTF-8") : input data \xffffffc3 in current source encoding could not be converted to Unicode
把unicode轉UTF-8
> x1 <- "\u5317\u4eac" > str_conv(x1, "UTF-8") [1] "北京"
3.4.2 str_to_upper,字符串大寫轉換。
函數定義:
str_to_upper(string, locale = "") str_to_lower(string, locale = "") str_to_title(string, locale = "")
參數列表:
- string: 字符串。
- locale:按哪種語言習慣排序
字符串大寫轉換:
> val <- "I am conan. Welcome to my blog! http://fens.me" # 全大寫 > str_to_upper(val) [1] "I AM CONAN. WELCOME TO MY BLOG! HTTP://FENS.ME" # 全小寫 > str_to_lower(val) [1] "i am conan. welcome to my blog! http://fens.me" # 首字母大寫 > str_to_title(val) [1] "I Am Conan. Welcome To My Blog! Http://Fens.Me"
字符串在平常的數據處理中經常用過,需要對字符串進行分割、連接、轉換等操作,本篇中通過介紹stringr,靈活的字符串處理庫,可以有效地提高代碼的編寫效率。有了好的工具,在用R語言處理字符串就順手了。
---------------------------------
常用功能:
# 合並字符串
fruit <- c("apple10", "banana"," ", "pe1ar", "pina22222pple","NA")
res <- str_c(1:4,fruit,sep=' ',collapse=' ')
str_c('I want to buy ',res,collapse=' ')
# 計算字符串長度
str_length(c("i", "like", "programming R", 123,res))
# 按位置取子字符串
str_sub(fruit, 1, 3)
# 子字符串重新賦值
capital <-toupper(str_sub(fruit,1,1))
str_sub(fruit, rep(1,4),rep(1,4)) <- capital
# 重復字符串
str_dup(fruit, c(1,2,3,4))
# 加空白
str_pad(fruit, 10, "both")
# 去除空白
str_trim(fruit)
# 根據正則表達式檢驗是否匹配
str_detect(fruit, "a$")
str_detect(fruit, "[aeiou]")
# 找出匹配的字符串位置(字符定位函數,返回匹配對象的首末位置)
str_locate(fruit, "a")
# 提取匹配的部分
str_extract(fruit, "[a-z]+")
str_match(fruit, "[a-z]+")
# 替換匹配的部分
str_replace(fruit, "[aeiou]", "-")
# 分割
str_split(res, " ")
str_extract(fruit, "\\d") # 提取數字
str_extract(fruit, "[a-z]+") #提取字母
注: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
包中的重要函數
函數 | 功能說明 | R Base中對應函數 |
---|---|---|
使用正則表達式的函數 | ||
str_extract() |
提取首個匹配模式的字符 | regmatches() |
str_extract_all() |
提取所有匹配模式的字符 | regmatches() |
str_locate() |
返回首個匹配模式的字符的位置 | regexpr() |
str_locate_all() |
返回所有匹配模式的字符的位置 | gregexpr() |
str_replace() |
替換首個匹配模式 | sub() |
str_replace_all() |
替換所有匹配模式 | gsub() |
str_split() |
按照模式分割字符串 | strsplit() |
str_split_fixed() |
按照模式將字符串分割成指定個數 | - |
str_detect() |
檢測字符是否存在某些指定模式 | grepl() |
str_count() |
返回指定模式出現的次數 | - |
其他重要函數 | ||
str_sub() |
提取指定位置的字符 | regmatches() |
str_dup() |
丟棄指定位置的字符 | - |
str_length() |
返回字符的長度 | nchar() |
str_pad() |
填補字符 | - |
str_trim() |
丟棄填充,如去掉字符前后的空格 | - |
str_c() |
連接字符 | paste(),paste0() |