【问题标题】:regex to match specific set of numbers or letters正则表达式匹配特定的数字或字母集
【发布时间】:2022-01-04 07:04:59
【问题描述】:

使用分类为各种“波”的调查数据,每个波标记为 1 - 14,或字母“A”或“E”,后跟变量名称。

比如要解析:

  • 3edu> 波:3,变量:educ
  • Aage > 波:A,变量:age

试过各种字符串,比如

^([0-9]?|A|E)(\\w+)

没有效果。请指教。

(将字符串与 R 一起使用)

【问题讨论】:

标签: r regex regex-group stringr


【解决方案1】:

如果您需要为数字范围创建正则表达式,请考虑使用automatic numeric range regex generator。匹配从114 的整数的正则表达式是(?:[1-9]|1[0-4])

所以,你需要使用

(?i)^(?P<wave>[1-9AE]|1[0-4])(?P<variable>\w+)

请参阅regex demo(?i) 设置不区分大小写模式,[1-9AE] 匹配非零数字或AE 字符。

在 R 中,您可以使用带有 namedCapture library 的命名捕获组:

x <- c("3educ","Aage","14abc","Ekajshklasjf")
library(namedCapture)
str_match_all_named(x, "(?i)^(?<wave>[1-9AE]|1[0-4])(?<variable>\\w+)")

输出:

[[1]]
     wave variable
[1,] "3"  "educ"  

[[2]]
     wave variable
[1,] "A"  "age"   

[[3]]
     wave variable
[1,] "1"  "4abc"  

[[4]]
     wave variable     
[1,] "E"  "kajshklasjf

【讨论】:

  • 非常有用,谢谢!
【解决方案2】:

没关系,我想我明白了:

^([0-9][0-9]?|a|e)(\\w+)

【讨论】:

  • 你的正则表达式也会选择15educ,即数字不限制在1到14之间。此外,[0-9]和\w不是互斥的。
  • 没关系,因为只有 1-14 个存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-01
  • 2023-03-14
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
相关资源
最近更新 更多