R数据对象处理函数(四)-grep+sub函数族

grep函数族可通过正则表达式在给定对象中搜索文本。grep输出向量下标或值,grepl返回匹配与否逻辑值。regexpr,gregexpr和regexec可以查找到某些字符在字符串中出现的具体位置和字符串长度信息,可以用于字符串的提取操作

grep(pattern, x, ignore.case= FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert =FALSE)
grepl(pattern, x,ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
grepRaw(pattern,x, offset = 1L, ignore.case = FALSE,value = FALSE, fixed = FALSE, all = FALSE,invert = FALSE)
ignore.case:FALSE大小写敏感,TRUE不敏感
perl:是否使用Perl风格的正则表达式
value:FALSE返回元素下标,TRUE返回匹配元素值
fixed:FALSE正则匹配,TRUE精确匹配
useBytes:FALSE按字符匹配,TRUE按字节匹配
invert:TRUE返回不匹配元素的下标或值
offset:指定匹配开始位置
all:TRUE返回所有匹配值,FALSE返回第一个匹配值
grepRaw("[or]","Tomorrow")	#2
grepRaw("[or]","Tomorrow", all = TRUE, offset = 3)	#从位置3开始向后搜索匹配
#如果原字符不是字节形式,charToRaw()强制字节化
regexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)	#向量,返回匹配字符的位置+匹配长度(只匹配第一次出现的),不匹配返回-1
gregexpr(pattern,text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)	#列表,返回匹配字符的位置+匹配长度(匹配多次),不匹配返回-1
regexec(pattern,text, ignore.case = FALSE, fixed = FALSE, useBytes =FALSE)	#列表,返回匹配字符的位置+匹配长度(只匹配第一次出现的),不匹配返回-1

attr(x,"match.length")	#x为regexpr,gregexpr,regexec的输出结果,返回匹配长度

regmatches(x,m,invert=F)	#提取regexpr,gregexpr,regexec中匹配或不匹配的字符
x <- c("cat","pct", "cctdcat", "caaaat", "ddd")
m <-regexpr("ca*t", x)
regmatches(x, m)

sub和gsub用于字符串替换,sub只替换第一次匹配的字符,gsub替换所有满足条件的匹配,R语言是传值不传址,故需进行赋值操作

sub(pattern,replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
gsub(pattern,replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
chartz(old,new,x) #将字符串x中的字符按照old->new进行替换,old和new长度必须一致,并按顺序替换

chartr("Nan","Bei", "Nanjing")

chartr("NB","BF", "Nanjing")

猜你喜欢

转载自blog.csdn.net/qq_38984677/article/details/81543060