R grepl
grepl tests a pattern against each input string and returns a logical vector of matches.
A simple example
grepl
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
Syntax
grepl("^[A-Z]{2}-[0-9]{3}$", labels)
Run this example in R
Save the program as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.R
Validate a vector of inventory labels
A scanner imports labels written to a prescribed identifier format. Match the complete label and extract only the required fields so a valid-looking substring cannot admit a malformed shipment.
labels <- c("AB-007", "A-007", "AB-007x")
valid <- grepl("^[A-Z]{2}-[0-9]{3}$", labels)
cat(labels[valid], "\n", sep = "")
cat(sum(!valid), "rejected\n")
AB-007 2 rejected
Anchoring both ends checks the complete identifier. A substring match alone could accept the valid-looking prefix of a longer, invalid label.
Validate a sample label
A lab assistant scans a four-character sample code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?
Catch an extra digit
A clerk accidentally types one additional digit in a shelf code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?