zoukankan      html  css  js  c++  java
  • R----stringr包介绍学习

     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( )
    • 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( )

    函数定义:str_trim(string, side = c("both", "left", "right"))
    参数列表:
    string: 字符串,字符串向量。
    side: 过滤方式,both两边都过滤,left左边过滤,right右边过滤
    去掉字符串的空格和TAB( )

    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: 字符串,字符串向量。
    字符串填充后的长度
    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: 字符串,字符串向量。
    • 设置一行所占的宽度。
    • indent: 段落首行的缩进值
    • exdent: 设置第二行后每行缩进 

    thanks_path <- file.path(R.home("doc"), "THANKS")
    thanks <- str_c(readLines(thanks_path), collapse = " ")
    thanks <- word(thanks, 1, 3, fixed(" "))
    cat(str_wrap(thanks), " ")
    cat(str_wrap(thanks, width = 70), " ") # 设置宽度为70个字符
    cat(str_wrap(thanks, width = 80, indent = 6, indent = 2), " ") # 设置宽度为80字符,首行缩进2字符
    cat(str_wrap(thanks, width = 80, indent = 6, exdent = 2), " ") # 设置宽度为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]", "11") # 把目标字符串所有出现的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 xffffffe3xffffffba 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 <- "u5317u4eac"
    > 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)
    制表符(009)
    换行符(00A)
    v 垂直制表符(u000B)
    f 换页符(00C)
    回车符(00D)
    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]
    [] 退格
    这个字符类很重要,需要记忆。
    描述方式:重复
    知识点
    {n,m} 匹配前一项至少n次,不超过m次
    {n,} 匹配前一项至少n次
    {n} 匹配前一项n次
    ? 等价于{0,1}
    + 等价于{1,}
    * 等价于{0,}
    x? 描述符后跟随一个"?"表示非贪婪匹配:从字符串中第一个可能匹配的位置,尽量少的匹配。如“??”、“{1,5}?”等。

    描述方式:选择、分组和引用
    “|”与逻辑表达式中的或类似,前后两者任意一个匹配,很好理解。而圆括号用来分组和引用,功能就比较复杂了。
    把单独的项组合成子表达式,以便重复、选择等操作。
    完整的模式中定义子模式,从而在匹配成功后从目标串中抽出和圆括号中的子模式匹配的部分。
    同一个正则表达式中后部引用前部的正则表达式,注意因为子表达式可以嵌套,所以它的位置是参与计数的左括号的位置。如果不创建带数字编码的引用,可以用"(?"和")"表示。
    举个简单的例子,如果要匹配单引号或双引号中的字符,可能会写成下面这样:
    /['"][^'"]*['"]/
    但是如果我们是想成对的匹配'abc'而不是匹配'abc"的话需要这么改写:
    /(['"])[^'"]*1/

    指定匹配位置的元素称为锚。
    ^ 匹配字符串开头,多行匹配一行的开头
    $ 匹配字符串结尾,多行匹配一行的结尾
     匹配一个单词的边界,位于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()
  • 相关阅读:
    suse12安装详解
    Centos7上部署openstack mitaka配置详解(将疑难点都进行划分)
    菜鸟帮你跳过openstack配置过程中的坑[文末新添加福利]
    openstack中dashboard页面RuntimeError: Unable to create a new session key. It is likely that the cache is unavailable.
    Multiple network matches found for name 'selfservice', use an ID to be more specific.报错
    查看 SELinux状态及关闭SELinux
    SELinux深入理解
    IP地址、子网掩码、网络号、主机号、网络地址、主机地址
    Oracle job procedure 存储过程定时任务
    POI文件导出至EXCEL,并弹出下载框
  • 原文地址:https://www.cnblogs.com/nxld/p/6062950.html
Copyright © 2011-2022 走看看