简体   繁体   English

R 正则表达式 / grep / grepl 用于字母后跟破折号和数字

[英]R regex / grep / grepl for letters followed by a dash and numbers

I'm trying to find the right grep notation to identify strings that have this pattern: Any number of letters followed by a dash (-) followed by any number of numbers.我正在尝试找到正确的 grep 表示法来识别具有这种模式的字符串:任意数量的字母后跟破折号 (-),后跟任意数量的数字。 For example ABC-123 would be a fit while 123-ABC or A1-B2 would not.例如, ABC-123适合,而123-ABCA1-B2则不适合。

I've tried grepl('[[A:Za:z]]\\-[[0:9]]','ABC-123') but am not getting the correct results.我试过grepl('[[A:Za:z]]\\-[[0:9]]','ABC-123')但没有得到正确的结果。

Any suggestions?有什么建议么?

We can change the range ( : ) to - and instead of [[ .我们可以将范围 ( : ) 更改为-而不是[[ In the pattern, we also specify the ^ and $ for start and end of string respectively.在模式中,我们还分别为字符串的开始和结束指定了^$ The + for letters and digits specify one or more...字母和数字的+指定一个或多个...

grepl("^[A-Za-z]+-[0-9]+$", str1)
#[1]  TRUE FALSE FALSE

Or if we want to use [[ ,或者,如果我们想使用[[

grepl("^[[:alpha:]]+-\\d+$", str1)
#[1]  TRUE FALSE FALSE

data数据

str1 <- c("ABC-123", "123-ABC", "A1-B2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM