library(stringr)
= c("A_A", "A_1.txt", "B_B", "B_123.txt") A
9 字符串处理(stringr包)
9.1 基础用法
字符串长度
str_length(A)
[1] 3 7 3 9
字符串截断
str_trunc(A,5)
[1] "A_A" "A_..." "B_B" "B_..."
字符串填充
str_pad(A,5,side="right",pad=" ")
[1] "A_A " "A_1.txt" "B_B " "B_123.txt"
字符串合并
# 简单合并
str_c(A,"_hello")
[1] "A_A_hello" "A_1.txt_hello" "B_B_hello" "B_123.txt_hello"
# 指定连接符
str_c(A,"_hello",
sep = "-", # 连接符
collapse = "|" # 把字符向量合并成一个字符串的连接符
)
[1] "A_A-_hello|A_1.txt-_hello|B_B-_hello|B_123.txt-_hello"
字符串拆分
str_split(A,pattern = "_")
[[1]]
[1] "A" "A"
[[2]]
[1] "A" "1.txt"
[[3]]
[1] "B" "B"
[[4]]
[1] "B" "123.txt"
9.2 字符串匹配
str_sub() # 用于提取置字符串某个位置区间的子串
str_detect() # 用于检测字符串是否匹配到
str_subset() # 筛选出匹配的字符串
str_locate()# 用于定位字符串中匹配到的起始和结束位置。/_all
str_extract() # 提取匹配到的子串 /_all
str_remove() # 移除匹配到的子串 /_all
str_replace() # 替换匹配到的子串 /_all
9.2.1 正则表达式
正则表达式是一种强大的文本处理规则,允许我们编写复杂的规则来匹配到想要的字符串。
^
:匹配行的开头。$
:匹配行的结尾。*
:匹配前面的元素零次或多次。 A*+
:匹配前面的元素一次或多次。?
:开启非贪婪模式。|
:匹配左右任意一个表达式。{}
:指定前面元素出现的次数。[]
:匹配方括号内的任意一个字符。.
:匹配任意字符。\\d
:匹配任何数字字符(等价于[0-9]
)。\\D
:匹配任何非数字字符。\\s
:匹配任何空白字符(如空格、制表符)。\\S
大写的S表示非空白字符\\w
:匹配字母文本(字母数字下划线中文)字符。\\W
大写的W表示非文本字符
9.2.2 匹配函数
str_sub
用于提取置字符串某个位置区间的子串
# 取出第2到第3位置的子字符串
str_sub(A,start = 2,end = 3)
[1] "_A" "_1" "_B" "_1"
str_detect
用于检测字符串是否匹配到
# 检测末尾是否是".txt",是的话返回TRUE
str_detect(A,pattern = "\\.txt$")
[1] FALSE TRUE FALSE TRUE
str_subset
筛选出匹配的字符串
# 检测是否含有数字,是的话返回整个字符串
str_subset(A,pattern = "\\d")
[1] "A_1.txt" "B_123.txt"
str_locate
用于定位字符串中匹配到的起始和结束位置。
str_locate_all(A,"txt")
[[1]]
start end
[[2]]
start end
[1,] 5 7
[[3]]
start end
[[4]]
start end
[1,] 7 9
str_extract
提取匹配到的子串 /_all
# 提取字符串中的数字
str_extract_all(A,"\\d+")
[[1]]
character(0)
[[2]]
[1] "1"
[[3]]
character(0)
[[4]]
[1] "123"
str_remove
移除匹配到的子串 /_all\
# 移除下划线及之后的任意字符
str_remove_all(A,"_.+")
[1] "A" "A" "B" "B"
str_replace
替换匹配到的子串 /_all
# 将下划线替换成中划线
str_replace_all(A,"_","-")
[1] "A-A" "A-1.txt" "B-B" "B-123.txt"
9.2.3 零宽断言
匹配两个标识符之间的字符串。
(?<=字符) # 左边的标识符
(?=字符) # 右边的标识符
# 取出下划线和".txt"之间的字符
str_extract("B_123.txt",pattern = "(?<=_).+(?=.txt)")
[1] "123"
9.3 其他
base R 中的用法
nchr() :返回字符串的长度。同str_length
paste():拼接字符串。同str_c