R语言R包详解——stringr包:字符处理
一切用法皆以说明书为准,想要了解该包,请多查阅说明书或者查看底层算法。
install.packages("stringr") # 安装R包
library(stringr) # 加载R包
packageVersion("stringr") # 查看加载的R包版本
help(package = "stringr") # 产看R包的具体信息
函数 | 功能 |
---|---|
str_c | 字符串拼接 |
str_trim | 去掉字符串的空格和TAB(\t) |
str_pad | 补充字符串的长度 |
str_dup | 复制字符串 |
str_wrap | 控制字符串输出格式 |
str_sub | 截取字符串 |
str_subset | 返回匹配的字符串 |
word | 从文本中提取单词 |
str_count | 字符串计数 |
str_length | 字符串长度 |
str_sort | 字符串值排序 |
str_order | 字符串索引排序,规则同str_sort |
str_split | 字符串分割 |
str_split_fixed | 字符串分割,同str_split |
str_detect | 检查匹配字符串的字符 |
str_match | 从字符串中提取匹配组。 |
str_match_all | 从字符串中提取匹配组,同str_match |
str_replace | 字符串替换 |
str_replace_all | 字符串替换,同str_replace |
str_replace_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 |
str_to_sentence | 字符转为语句 |
str_glue | 提取字符串中的变量 |
str_remove | 字符删除 |
str_remove_all | 字符删除,规则同str_remove |
str_c(..., sep = "", collapse = NULL)
参数列表:
…: 多参数的输入
sep: 用于字符串拼接,为字符串的分割符。
collapse: 用于向量拼接,为向量字符串的分割符。
> # 默认无向量分割符拼接
> str_c("a","b")
[1] "ab"
> # 指定向量分隔符
> str_c("a","b",sep = "_")
[1] "a_b"
> # 指定向量折叠符
> str_c(c("a","b","c"),collapse = "_")
[1] "a_b_c"
> # 混合应用
> str_c(c("a","b"),c("c","d"),sep = "/",collapse = "_")
[1] "a/c_b/d"
> #相同点
> ############
> # 向量拼接字符串,collapse参数的行为一致
> str_c(c("a","b","c"), collapse = "") #collapse 将一个向量的所有元素连接成一个字符串,collapse设置元素间的连接符
[1] "abc"
> paste(c("a","b","c"), collapse = "")
[1] "abc"
> #不同点
> ############
> str_c('a','b') #把多个字符串拼接为一个大的字符串。
[1] "ab"
> paste('a','b') # 多字符串拼接,默认的sep参数行为不一致
[1] "a b"
> #拼接有NA值的字符串向量,对NA的处理行为不一致
> str_c(c("a", NA, "b"), "-d") #若为空,则无法连接
[1] "a-d" NA "b-d"
> paste(c("a", NA, "b"), "-d") #即使空,也可连接
[1] "a -d" "NA -d" "b -d"
> str_c(str_replace_na(c("a", NA, "b")), "-d") #需要进行处理才可连接
[1] "a-d" "NA-d" "b-d"
# str_replace_na用于将值NA替换为字符“NA”
str_trim(string, side = c("both", "left", "right"))
参数列表:
string: 字符串,字符串向量。
side: 过滤方式,both两边都过滤,left左边过滤,right右边过滤
> # 删除字符串两侧的空格
> str_trim(" a ",side = "both")
[1] "a"
> # 删除字符串左侧的空格
> str_trim(" a ",side = "left")
[1] "a "
> # 删除字符串右侧的空格
> str_trim(" a ",side = "right")
[1] " a"
str_pad(string, width, side = c("left", "right", "both"), pad = " ", use_width = TRUE)
参数列表:
string: 字符串,字符串向量
width: 字符串填充后的长度(若指定的width长度小于string长度,则无效扩充)
side: 填充方向,both两边都填充,left左边填充,right右边填充
pad: 用于填充的字符(要求单字符)
use_width: 若为False,则返回string(不扩充)
> # string ≤ width 无效扩充
> str_pad("aaaaa",3)
[1] "aaaaa"
> # string > width 默认为从左侧扩充
> str_pad("aaaaa",10)
[1] " aaaaa"
> # 更改扩充方式和填充内容,both方式下,非对称时优先补充至右侧
> str_pad("aaaaa",10,side = "both",pad = "*")
[1] "**aaaaa***"
str_dup(string, times)
参数列表:
string:需要重复处理的字符串
times:指定重复的次数
> # 字符串复制
> str_dup("a",2)
[1] "aa"
> # 向量复制
> str_dup(c("a","b","c"),1:3)
[1] "a" "bb" "ccc"
> # 组合使用
> str_c(c("a","b","c"),str_dup(c(1,2,3),1:3),sep = "_",collapse = "/")
[1] "a_1/b_22/c_333"
str_wrap(string, width = 80, indent = 0, exdent = 0, whitespace_only = TRUE))
参数列表:
string: 字符串,字符串向量。
width: 设置一行所占的宽度。
indent: 段落首行的缩进值(缩进字符不纳入width的考量内)。
exdent: 设置第二行及之后每行缩进(缩进字符不纳入width的考量内)。
whitespace_only: 若为Ture则换行只会发生在空格处,若为False则换行也会发生在非字符(,/-等)处。
> text <- "This is a-long-string that needs to be wrapped to fit within a specified width."
> # 首行不缩进,后面每行缩进两字符(缩进字符不纳入width的考量内)
> str_wrap(text, width = 14,indent = 0,exdent = 2)
[1] "This is\n a-long-string\n that needs\n to be\n wrapped to\n fit within\n a specified\n width."
> # 缩进会发生在非字符处
> str_wrap(text, width = 14,indent = 0,exdent = 2,whitespace_only = F)
[1] "This is a-\n long-\n string that\n needs to be\n wrapped to\n fit within\n a specified\n width."
str_sub(string, start = 1L, end = -1L)
参数列表:
string: 字符串,字符串向量。
start : 开始位置
end : 结束位置
> # 字符过滤(正向索引)
> str_sub(string = "banana",start = 1,end = 3)
[1] "ban"
> # 字符过滤(反向索引)
> str_sub(string = "banana",start = -2,end = -1)
[1] "na"
> # 字符过滤,并赋值
> x <- "banana"
> str_sub(string = x,start = 1,end = 1) <- "A"
> print(x)
[1] "Aanana"
> # 分2段截取字符串
> str_sub("banana", c(1, 2), c(3, -2))
[1] "ban" "anan"
str_subset(string, pattern)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配的字符。
> fruit <- c("apple", "banana", "pear", "pinapple")
> ##返回含字符'ap'的字符串
> str_subset(fruit, "ap")
[1] "apple" "pinapple"
> # 运用正则表达式进行详细的字符匹配
> ## 匹配开头
> str_subset(fruit, "^a")
[1] "apple"
> ## 匹配结尾为a的字符串
> str_subset(fruit, "a$")
[1] "banana"
> ##返回含'aeiou'任一个字符的单词
> str_subset(fruit, "[aeiou]")
[1] "apple" "banana" "pear" "pinapple"
> #匹配任意字符,即可以实现丢弃空值
> str_subset(c("a", NA, "b"), ".")
[1] "a" "b"
word(string, start = 1L, end = start, sep = fixed(" "))
参数列表:
string: 字符串,字符串向量。
start: 开始的单词。
end: 结束的单词。
sep: 分隔符。
> sentences <- c("I saw a cat, it sat down","Maybe you-were-right")
> #提取第二个单词到最后一个单词
> word(sentences, 2, -1)
[1] "saw a cat, it sat down" "you-were-right"
> #整个句子从第一~三个单词到最后一个单词
> word(sentences[1], 1:3, -1)
[1] "I saw a cat, it sat down" "saw a cat, it sat down" "a cat, it sat down"
> # 指定分隔符
> word(sentences, 2, -1, sep = ",")
[1] " it sat down" NA
> word(sentences, 2, -1, sep = "-")
[1] NA "were-right"
str_count(string, pattern = "")
参数列表:
string: 字符串,字符串向量。
pattern: 匹配的字符。
> # 单个目标字符计数
> str_count(string = c("sql","json","java"),pattern = "s")
[1] 1 1 0
> # 多个目标字符计数
> str_count(string = c("sql","json","java"),pattern = c("s","j","a"))
[1] 1 1 2
> # 统计字符长度
> str_count(string = c("sql","json","java"))
[1] 3 4 4
str_length(string)
参数列表:
string: 字符串,字符串向量。
> str_length(c("I", "am", "福旺旺", NA))
[1] 1 2 3 NA
str_sort(x, decreasing = FALSE, na_last = TRUE, locale = "en", numeric = FALSE,...)
参数列表:
x: 字符串,字符串向量
decreasing: 排序方向
na_last: NA值的存放位置,一共3个值,TRUE放到最后,FALSE放到最前,NA过滤处理
locale: 按哪种语言习惯排序,默认为"en" (English)
numeric: 若为Ture,则将数字当作数值型进行排序处理,否则按照字符型排序处理
> # 字符向量升序排序,返回字符向量
> str_sort(c("sql","json","python",NA))
[1] "json" "python" "sql" NA
> # 字符向量降序排序,返回字符向量,并丢弃掉NA值
> str_sort(c("sql","json","python",NA),decreasing = TRUE, na_last = NA)
[1] "sql" "python" "json"
> # 字符向量升序排序,返回字符向量,并将NA值放在第一个
> str_sort(c("sql","json","python",NA),na_last = F)
[1] NA "json" "python" "sql"
str_order(x, decreasing = FALSE, na_last = TRUE, locale = "en", numeric = FALSE,...)
参数列表:
x: 字符串,字符串向量
decreasing: 排序方向
na_last: NA值的存放位置,一共3个值,TRUE放到最后,FALSE放到最前,NA过滤处理
locale: 按哪种语言习惯排序,默认为"en" (English)
numeric: 若为Ture,则将数字当作数值型进行排序处理,否则按照字符型排序处理
> # 字符向量升序排序,返回索引向量
> str_order(c("sql","json","python",NA))
[1] 2 3 1 4
> # 字符向量降序排序,返回索引向量,并丢弃掉NA值
> str_order(c("sql","json","python",NA),decreasing = TRUE, na_last = NA)
[1] 1 3 2
> # 字符向量升序排序,返回索引向量,并将NA值放在第一个
> str_order(c("sql","json","python",NA),na_last = F)
[1] 4 2 3 1
str_split(string, pattern, n = Inf, simplify = FALSE)
str_split_fixed(string, pattern, n)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配的字符。
n: 分割个数 #最后一组就不会被分割
simplify: False 返回列表,Ture 返回矩阵(有了这个参数,那str_split_fixed就属于旧时代的遗物了)
> # 字符分割,返回列表
> str_split(string = "ba-na-na",pattern = "")
[[1]]
[1] "b" "a" "-" "n" "a" "-" "n" "a"
> # 字符分割3次,返回列表
> str_split(string = "ba-na-na",pattern = "", n = 3)
[[1]]
[1] "b" "a" "-na-na"
> # 字符分割,返回矩阵
> str_split(string = "ba-na-na",pattern = "-",simplify = T)
[,1] [,2] [,3]
[1,] "ba" "na" "na"
> # 字符分割,需要指定分割块数
> str_split_fixed(string = "ba-na-na",pattern = "-", n = Inf)
[,1] [,2] [,3]
[1,] "ba" "na" "na"
str_detect(string, pattern)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
> # 检测字符串中是否包含s
> str_detect(string = c("sql","json","java"),pattern = "s")
[1] TRUE TRUE FALSE
> # 检测字符串中是否以s开头
> str_detect(string = c("sql","json","java"),pattern = "^s")
[1] TRUE FALSE FALSE
str_match(string, pattern)
str_match_all(string, pattern)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
> val <- c("aabbcc", 123, "1ab")
> # 从字符串中提取匹配组
> # 匹配字符a,并返回对应的字符
> str_match(val, "a")
[,1]
[1,] "a"
[2,] NA
[3,] "a"
> #从字符串中提取匹配组,以字符串matrix格式返回
> str_match_all(val, "a")
[[1]]
[,1]
[1,] "a"
[2,] "a"
[[2]]
[,1]
[[3]]
[,1]
[1,] "a"
> # 匹配字符0-9,限1个,并返回对应的字符
> str_match(val, "[0-9]")
[,1]
[1,] NA
[2,] "1"
[3,] "1"
> # 匹配字符0-9,不限数量,并返回对应的字符
> str_match(val, "[0-9]*")
[,1]
[1,] ""
[2,] "123"
[3,] "1"
> # 匹配每一个字符0-9,并返回对应的字符
> str_match_all(val, "[0-9]")
[[1]]
[,1]
[[2]]
[,1]
[1,] "1"
[2,] "2"
[3,] "3"
[[3]]
[,1]
[1,] "1"
str_replace(string, pattern, replacement)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
replacement: 用于替换的字符。
> #替换第一个匹配的字符# 把目标字符串第一个出现的a或b,替换为-
> str_replace(val, "[ab]", "-")
[1] "-bc" "123" "c-a"
> #替换所有匹配的字符 # 把目标字符串所有出现的a或b,替换为-
> str_replace_all(val, "[ab]", "-")
[1] "--c" "123" "c--"
str_replace_na(string, replacement = "NA")
参数列表:
string: 字符串,字符串向量。
replacement : 用于替换的字符。
> # 把NA值替换为字符串
> str_replace_na(c(NA,'NA',"abc"),'x')
[1] "x" "NA" "abc"
str_locate(string, pattern)
str_locate_all(string, pattern)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
> val <- c("aabbcc","123","bacabc")
> # 用字符匹配
> str_locate(val, "a")
start end
[1,] 1 1
[2,] NA NA
[3,] 2 2
> # 用向量匹配
> str_locate(val, c("a", 12, "b"))
start end
[1,] 1 1
[2,] 1 2
[3,] 1 1
> # 以字符串matrix格式返回
> str_locate_all(val, "a")
[[1]]
start end
[1,] 1 1
[2,] 2 2
[[2]]
start end
[[3]]
start end
[1,] 2 2
[2,] 4 4
> # 匹配a或b字符,以字符串matrix格式返回
> str_locate_all(val, "[ab]")
[[1]]
start end
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
[[2]]
start end
[[3]]
start end
[1,] 1 1
[2,] 2 2
[3,] 4 4
[4,] 5 5
str_extract(string, pattern, group = NULL)
str_extract_all(string, pattern, simplify = FALSE)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
group: 如果提供,则不会返回完整的匹配,而是从指定的捕获组返回匹配的文本。
simplify: 返回值,TRUE返回matrix,FALSE返回字符串向量
> shopping_list <- c("apples x4", "bag of flour", "bag of sugar", "milk x2")
> # 提取所有数字,\转义,\d正则表达式,等价于[0-9]查找所有数字。
> str_extract(shopping_list, "\\d")
[1] "4" NA NA "2"
> # 提取小写字母,+匹配前面的子表达式一次或多次。
> str_extract(shopping_list, "[a-z]+")
[1] "apples" "bag" "bag" "milk"
> # 提取小写字母,{1,4}匹配前面的子表达式最少1次,最多4次。
> str_extract(shopping_list, "[a-z]{1,4}")
[1] "appl" "bag" "bag" "milk"
> # \b匹配一个单词边界,即字与空格间的位置。若左右两侧皆加上\b则表示取一个位于两个空格之间的完整字符串。
> str_extract(shopping_list, "\\b[a-z]{1,4}\\b")
[1] NA "bag" "bag" "milk"
> # ()标记一个子表达式的开始和结束位置。配合group参数,可以精确的挑出想要的子表达式。
> str_extract(shopping_list, "([a-z]+) of ([a-z]+)")
[1] NA "bag of flour" "bag of sugar" NA
> str_extract(shopping_list, "([a-z]+) of ([a-z]+)", group = 1)
[1] NA "bag" "bag" NA
> str_extract(shopping_list, "([a-z]+) of ([a-z]+)", group = 2)
[1] NA "flour" "sugar" NA
> # 提取所有匹配字符,返回列表的形式。
> str_extract_all(shopping_list, "[a-z]+")
[[1]]
[1] "apples" "x"
[[2]]
[1] "bag" "of" "flour"
[[3]]
[1] "bag" "of" "sugar"
[[4]]
[1] "milk" "x"
> str_extract_all(shopping_list, "\\b[a-z]+\\b")
[[1]]
[1] "apples"
[[2]]
[1] "bag" "of" "flour"
[[3]]
[1] "bag" "of" "sugar"
[[4]]
[1] "milk"
> str_extract_all(shopping_list, "\\d")
[[1]]
[1] "4"
[[2]]
character(0)
[[3]]
character(0)
[[4]]
[1] "2"
> # Simplify参数,将返回值转化为矩阵形式
> str_extract_all(shopping_list, "\\b[a-z]+\\b", simplify = TRUE)
[,1] [,2] [,3]
[1,] "apples" "" ""
[2,] "bag" "of" "flour"
[3,] "bag" "of" "sugar"
[4,] "milk" "" ""
> str_extract_all(shopping_list, "\\d", simplify = TRUE)
[,1]
[1,] "4"
[2,] ""
[3,] ""
[4,] "2"
> # 将所有的单词提取出来(剔除标点之类的非字符)
> str_extract_all("This is, suprisingly, a sentence.", boundary("word"))
[[1]]
[1] "This" "is" "suprisingly" "a" "sentence"
str_conv(string, encoding)
参数列表:
string: 字符串,字符串向量。
encoding: 编码名。
> x <- rawToChar(as.raw(177))
> x
[1] "\xb1"
> str_conv(x, "ISO-8859-2") # Polish "a with ogonek"
[1] "ą"
> str_conv(x, "ISO-8859-1") # Plus-minus
[1] "±"
str_to_upper(string, locale = "en")
str_to_lower(string, locale = "en")
参数列表:
string: 字符串,字符串向量
locale: 按哪种语言习惯排序,默认为"en" (English)
> val <- "This is a dog. It is so cute."
> # 全大写
> str_to_upper(val)
[1] "THIS IS A DOG. IT IS SO CUTE."
> # 全小写
> str_to_lower(val)
[1] "this is a dog. it is so cute."
str_to_title(string, locale = "en")
参数列表:
string: 字符串,字符串向量
locale: 按哪种语言习惯排序,默认为"en" (English)
> val <- "This is a dog. It is so cute."
> # 每个单词的首字母都大写
> str_to_title(val)
[1] "This Is A Dog. It Is So Cute."
str_to_sentence(string, locale = "en")
参数列表:
string: 字符串,字符串向量
locale: 按哪种语言习惯排序,默认为"en" (English)
> val <- "This is a dog. It is so cute."
> # 只有第一个单词的首字母大写
> str_to_sentence(val)
[1] "This is a dog. It is so cute."
参数传递方式:str_glue函数使用…参数来传递变量,而str_glue_data函数使用data参数来传递变量。在str_glue_data中,可以通过data参数指定一个数据框(data frame),其中包含了要插入到字符串中的变量。
变量引用方式:在str_glue函数中,可以直接引用变量名,例如"{var}“。而在str_glue_data函数中,需要使用花括号和句点的组合来引用变量,例如”{.data$var}"。这是因为str_glue_data需要通过data参数指定数据框,所以需要使用句点来引用数据框中的变量。
环境设置:str_glue函数默认使用当前环境来获取变量值,而str_glue_data函数使用data参数指定的数据框作为环境来获取变量值。这意味着在str_glue_data中,可以直接使用数据框中的变量名,而不需要在变量名前加上数据框的名称。
str_glue(..., .sep = "", .envir = parent.frame())
str_glue_data(.x, ..., .sep = "", .envir = parent.frame(), .na = "NA")
参数列表:
...:表示要插入到字符串中的变量。可以是一个或多个变量,用逗号分隔。
.sep:表示多个变量之间的分隔符,默认为空格。例如,如果设置为"-",则多个变量之间将用"-"分隔。
.envir:表示要从中获取变量值的环境,默认为当前环境。可以是一个环境对象或一个整数,表示要获取变量值的环境的层数。
.na:表示当变量值为NA时的替代文本,默认为空字符串。例如,如果设置为"NA",则当变量值为NA时,将使用"NA"替代。
> name <- "Fred"
> age <- 50
> anniversary <- as.Date("1991-10-12")
> # 使用全局变量
> str_glue(
+ "My name is {name}, ",
+ "my age next year is {age + 1}, ",
+ "and my anniversary is {format(anniversary, '%A, %B %d, % ..." ... [TRUNCATED]
My name is Fred, my age next year is 51, and my anniversary is 星期六, 十月 12, 1991.
> # 双{{}}会失效
> str_glue("My name is {name}, not {{name}}.")
My name is Fred, not {name}.
> # 使用局部变量
> str_glue(
+ "My name is {name}, ",
+ "and my age next year is {age + 1}.",
+ name = "Joe",
+ age = 40
+ )
My name is Joe, and my age next year is 41.
> # 调用数据框
> mtcars %>% str_glue_data("{rownames(.)} has {hp} hp")
Mazda RX4 has 110 hp
Mazda RX4 Wag has 110 hp
Datsun 710 has 93 hp
Hornet 4 Drive has 110 hp
Hornet Sportabout has 175 hp
Valiant has 105 hp
...
str_remove(string, pattern)
str_remove_all(string, pattern)
参数列表:
string: 字符串,字符串向量。
pattern: 匹配字符。
> # 删除第一个匹配到的字符
> str_remove(string = c("abc","123","bac"),pattern = "[ab]")
[1] "bc" "123" "ac"
> # 删除所有匹配到的字符
> str_remove_all(string = c("abc","123","bac"),pattern = "[ab]")
[1] "c" "123" "c"
boundary(
type = c("character", "line_break", "sentence", "word"),
skip_word_none = NA,
...
)
参数列表:
type: 要检测的边界类型
character
每一个字符
line_break
换行符
sentence
一句话(以"."结尾,且句子前后有空格分开)
word
单词(前后有空格隔开)
skip_word_none: 忽略不包含任何字符或数字的“单词”一一例如标点符号。默认NA仅在单词边界上拆分时才会跳过此类“单词”。
> words <- c("These are some words.")
> str_count(words, boundary("word"))
[1] 4
> str_split(words, " ")[[1]]
[1] "These" "are" "" "" "some" "words."
> str_split(words, " ")
[[1]]
[1] "These" "are" "" "" "some" "words."
> str_split(words, boundary("word"))[[1]]
[1] "These" "are" "some" "words"
coll(pattern, ignore_case = FALSE, locale = "en", ...)
参数列表:
pattern: 匹配字符
ignore_case: Ture不区分大小写差异,False区分差异
locale: 按哪种语言习惯排序,默认为"en" (English)
> pattern <- "a.b"
> strings <- c("abb", "a.b")
> str_detect(strings, pattern)
[1] TRUE TRUE
> str_detect(strings, fixed(pattern))
[1] FALSE TRUE
> str_detect(strings, coll(pattern))
[1] FALSE TRUE
>
> # coll() is useful for locale-aware case-insensitive matching
> i <- c("I", "\u0130", "i")
> i
[1] "I" "İ" "i"
> str_detect(i, fixed("i", TRUE))
[1] TRUE FALSE TRUE
> str_detect(i, fixed("i", FALSE))
[1] FALSE FALSE TRUE
> str_detect(i, coll("i", TRUE))
[1] TRUE FALSE TRUE
> str_detect(i, coll("i", TRUE, locale = "tr"))
[1] FALSE TRUE TRUE
fixed(pattern, ignore_case = FALSE)
参数列表:
pattern: 匹配字符
ignore_case: Ture不区分大小写差异,False区分差异
> pattern <- "a.b"
> strings <- c("abb", "a.b")
> str_detect(strings, pattern)
[1] TRUE TRUE
> str_detect(strings, fixed(pattern))
[1] FALSE TRUE
> str_detect(strings, coll(pattern))
[1] FALSE TRUE
>
> # coll() is useful for locale-aware case-insensitive matching
> i <- c("I", "\u0130", "i")
> i
[1] "I" "İ" "i"
> str_detect(i, fixed("i", TRUE))
[1] TRUE FALSE TRUE
> str_detect(i, fixed("i", FALSE))
[1] FALSE FALSE TRUE
> str_detect(i, coll("i", TRUE))
[1] TRUE FALSE TRUE
> str_detect(i, coll("i", TRUE, locale = "tr"))
[1] FALSE TRUE TRUE
在R语言的stringr包中,coll和fixed函数都是用于进行字符串匹配和替换的函数,但它们有一些区别。
coll函数:coll函数用于进行基于正则表达式的字符串匹配和替换。它使用的是基于Unicode的正则表达式引擎,可以进行更复杂的模式匹配。coll函数可以接受正则表达式作为模式参数,并根据模式进行字符串的匹配和替换。
fixed函数:fixed函数用于进行基于固定字符串的字符串匹配和替换。它不使用正则表达式,而是直接按照给定的固定字符串进行匹配和替换。fixed函数适用于简单的字符串匹配,不需要考虑正则表达式的特殊字符。
总的来说,coll函数适用于复杂的字符串匹配和替换,可以使用正则表达式进行模式匹配。而fixed函数适用于简单的字符串匹配和替换,不需要考虑正则表达式的特殊字符。选择使用哪个函数取决于具体的需求和字符串处理的复杂程度。
regex(
pattern,
ignore_case = FALSE,
multiline = FALSE,
comments = FALSE,
dotall = FALSE,
...
)
参数列表:
pattern: 匹配字符
ignore_case: Ture不区分大小写差异,False区分差异
multiline: 如果TRUE,则$和^匹配每一行的开头和结尾。如果为FALSE(默认),则只匹配输入的开始和结束
comments: 如果为TRUE,则忽略空格和以#开头的注释。用\\转义文本空间
dotall: 如果为TRUE,将匹配行终止符(将换行符\n当作是一般字符去识别)。
> # Regular expression variations
> str_extract_all("The Cat in the Hat", "[a-z]+")
[[1]]
[1] "he" "at" "in" "the" "at"
> # ignore_case = Ture 忽视大小写
> str_extract_all("The Cat in the Hat", regex("[a-z]+", TRUE))
[[1]]
[1] "The" "Cat" "in" "the" "Hat"
> # multiline = TRUE 匹配每一行
> str_extract_all("a\nb\nc", "^.")
[[1]]
[1] "a"
> str_extract_all("a\nb\nc", regex("^.", multiline = TRUE))
[[1]]
[1] "a" "b" "c"
> # dotall = TRUE 匹配换行符
> str_extract_all("a\nb\nc", "a.")
[[1]]
character(0)
> str_extract_all("a\nb\nc", regex("a.", dotall = TRUE))
[[1]]
[1] "a\n"
除了stringr包之外,R语言中还有其他一些常用的用于字符处理的包,包括:
stringi:stringi包是一个功能强大的字符串处理包,提供了大量的函数和方法来处理和操作字符串。它支持多种语言和字符编码,具有较高的性能。
stringdist:stringdist包提供了一系列计算字符串之间距离的函数,例如编辑距离、汉明距离等。它可以用于字符串匹配、聚类和分类等任务。
stringi:stringi包是另一个用于字符串处理的包,它提供了一系列函数来处理和操作字符串,包括字符串匹配、替换、分割、提取等功能。
string:string包提供了一些基本的字符串处理函数,例如字符串匹配、替换、分割等。它是R语言的基础包,无需额外安装。
stringdistroy:stringdistroy包是stringdist包的扩展,提供了更多的字符串距离计算方法,例如Jaro-Winkler距离、Smith-Waterman距离等。
这些包都提供了丰富的函数和方法来处理和操作字符串,具体选择哪个包取决于您的需求和偏好。您可以通过在R中使用install.packages()
命令安装这些包,并使用library()
命令加载它们。同时,您也可以通过使用?
命令在R中获取更详细的帮助信息。