简体   繁体   中英

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. For example ABC-123 would be a fit while 123-ABC or A1-B2 would not.

I've tried grepl('[[A:Za:z]]\\-[[0:9]]','ABC-123') but am not getting the correct results.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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