string <- c("Hiphopopotamus","Rhymenoceros","time for bottomless lyrics")
pattern <- "t.m"
#分割字符串
strsplit(string,pattern)#按关键词分割字符串
stringr::str_split(string,pattern)
#定位关键字
regexpr(pattern,string)#返回每个字符串第一次匹配关键词的位置和长度
gregexpr(pattern,string)#返回全部匹配的位置和长度,无匹配则填-1
stringr::str_locate(string,pattern)#返回第一次匹配关键词的首尾位置(好用)
stringr::str_locate_all(string,pattern)#返回全部匹配的首尾位置(好用)
#检测关键词
grep(pattern,string)#关键词匹配哪几个字符串
grep(pattern,string,value=T)#返回包含关键词的字符串
grepl(pattern,string)#判断关键词与字符串是否匹配
stringr::str_detect(string,pattern)
#提取关键词
regmatches(string,regexpr(pattern,string))
regmatches(string,gregexpr(pattern,string))
stringr::str_extract(string,pattern)
stringr::str_extract_all(string,pattern)
stringr::str_extract_all(string,pattern,simplify=T)
stringr::str_match(string,pattern)
stringr::str_match_all(string,pattern)
#关键词替换
sub(pattern,"*",string)
gsub(pattern,"*",string)
stringr::str_replace(string,pattern,"*")
stringr::str_replace_all(string,pattern,"*")
参考:
https://mp.weixin.qq.com/s/be2Dz-gyocp9Cbm5dkoQuQ
https://www.math.pku.edu.cn/teachers/lidf/course/fts/ftsnotes/html/_ftsnotes/fts-ltscases-gas.html#
#https://faculty.chicagobooth.edu/-/media/faculty/ruey-s-tsay/teaching/introts/w-petroprice.txt
la <- readLines("E:/w-petroprice.txt")
#https://www.jianshu.com/p/11bbfa8e98c5
la <- gsub("\\s+", " ", la)
la <- gsub("^\\s+|\\s$", "", la)
c(
head(la),
tail(la)
)
da1 <- readr::read_table2(
paste(la, collapse="\n")
)
http://www.mathsccnu.com/forum.php?mod=viewthread&tid=5162&extra=page%3d1
#https://www.jianshu.com/p/b3f70d96455f
#https://blog.csdn.net/lztttao/article/details/82086346
#https://www.jianshu.com/p/11bbfa8e98c5
string <- c("1554","4456","1552465")
pattern <- "[^5]" # 不为5的元素
stringr::str_locate(string,pattern) # 首次出现在字符串的哪个位置
stringr::str_locate_all(string,pattern) # 出现在字符串的哪个位置
sub(pattern,"",string) # 替换第一个不为5的元素
gsub(pattern,"",string) # 替换所有不为5的元素(只保留元素5)
pattern <- "5" # 效果与单个匹配"[5]"相同
stringr::str_locate(string,pattern) # 查找元素5
stringr::str_locate_all(string,pattern)
sub(pattern,"",string) # 删除元素5
gsub(pattern,"",string)
x <- "a1;bb12; ccc123;dddd1234;eeeee12345;ffffff123456;ggggggg1234567"
gsub("\\d","_",x) #所有数字均被单独替换,一次匹配1个字符
gsub("\\d+","_",x) #所有数字均被整体替换,一次匹配1个以上字符
gsub("\\d ","_",x) #匹配无效
gsub("\\d{3}","_",x) #一次匹配3个字符
gsub("\\d{3,}","_",x) #一次匹配3个以上字符
gsub("\\d{3,5}","_",x) #一次匹配3到5个字符
gsub("\\d?","_",x) #所有数字均被单独替换,一次匹配1个以下字符(处理词首)
gsub("\\d*","_",x) #所有数字均被整体替换,一次匹配0个以上字符(处理词首)