Library contents

R grepl

grepl tests a pattern against each input string and returns a logical vector of matches.

A simple example

grepl

  1. Start with "12" and the pattern ^[0-9]+$
  2. Do this Match the whole string
  3. Result Match
Both characters are digits, so the pattern covers the text from beginning to end.

Syntax

R 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.

From the programcat(labels[valid], "\n", sep = "")
First output lineAB-007
Lesson.R
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")
Output
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.

R documentation for grepl

Advertisements

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?

GivenPH07
Worked resultAccept

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?

GivenAR123
Worked resultReview