【问题标题】:Regex in R: How to extract certain letters from alphanumeric element in character vector?R中的正则表达式:如何从字符向量中的字母数字元素中提取某些字母?
【发布时间】:2015-01-17 14:27:57
【问题描述】:

例如,我有以下字母数字元素的字符向量,其中包含元素内某处的状态缩写:

strings <- c("0001AZ226", "0001CA243", "0NA01CT134", "0001CT1NA", "0001ID112", "NAVA230")

如何提取字母,不包括 NA?即,

somefunction(strings)
[1] "AZ"  "CA"  "CT"  "CT"  "ID"  "VA"

我以前使用正则表达式来删除每个元素的所有非整数,但从不删除所有数字,只删除字母 N 和 A。

这是我尝试过的,但没有奏效:

 sub(paste(LETTERS[c(2:13,15:26)], collapse = "|"), "", strings, fixed = TRUE)

【问题讨论】:

  • gsub('\\d|NA', '', strings) \d 是数字的缩写,其他见?regex
  • 如果 R 支持,可以使用环视来完成。

标签: regex r


【解决方案1】:

一个简单的解决方案:

gsub("\\d+|NA", "", strings)
# [1] "AZ" "CA" "CT" "CT" "ID" "VA"

【讨论】:

    【解决方案2】:

    可以使用 looarounds 来完成。

     # (?i)(?:(?!na|(?<=n)(?=a))[a-z])+
    
     (?i)           # Case insensitive modifier (or use as regex flag)
     (?:            # Cluster group
          (?!            # Negative assertion
               na             # Not NA ahead
            |  (?<= n )       # Not N behind,
               (?= a )        # and A ahead (at this location) 
          )              # End Negative assertion
          [a-z]          # Safe, grab this single character
     )+             # End Cluster group, do 1 to many times
    

    仅匹配这些"AZ" "CA" "CT" "CT" "ID" "VA"

    【讨论】:

      【解决方案3】:

      只要状态出现后仅跟三个字符。

      strings.stripped <- gsub("([A-Z]{2}).{3}$", "\\1", strings)
      

      【讨论】:

        【解决方案4】:

        state 数据集默认可用。看着:

         ?state
        
        sts <- paste(state.abb,collapse="|")
        
        sub(paste0( "(.+)(", sts, ")(.+)"), "\\2", strings)
        [1] "AZ" "CA" "CT" "CT" "ID" "VA"
        

        有人尝试编辑此内容并致电dput(states.abb),然后将其粘贴到新作业中。鉴于state 始终可用,这是完全没有必要的,因此我拒绝了。我能看到的唯一价值可能是建议人们实际查看帮助页面并说明 state.abb 的样子:

        ?state
        dput(state.abb)
        #c("AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", 
        ... snipped the rest.
        

        【讨论】:

        • @BondedDust 这是一个非常优雅的解决方案!也不知道state 数据集。谢谢。
        • @BondedDust 你错过了我编辑的重点。 DC 不在state.abb 中。也许我的一些编辑被切断了?我明确表示“如果您想将此解决方案扩展到华盛顿、美国领土等”。
        • 如果您想将向量扩展到地区、保护国、非国家联邦、军事单位和“领土”的邮政名称缩写(在我看来,这对美国来说似乎有点过时) ,使用起来不是更简单吗:c(state.abb, "DC", "PR","VI","GU","MP","AA","AE","AP", "FM","MH","PW")
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-09
        • 2012-12-30
        • 2011-09-05
        • 1970-01-01
        • 2023-03-22
        • 2019-08-07
        相关资源
        最近更新 更多