R sub
Replace just the first run of digits when updating the first field on a label.
A simple example
sub
- Start with "a1b2"
- Do this Replace only the first digit with *
- Result "a*b2"
Syntax
sub("[0-9]+", "*", value)
Run these examples in R
Save one example at a time as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.RMask just the first locker number
A service desk displays an identifier where bystanders could see it. Replace the intended numeric field or digit runs while preserving the rest of the record for the operator.
value <- "B12 / C34"
cat(sub("[0-9]+", "*", value), "\n", sep = "")
B* / C34
The second number stays visible.
Handle a label without a number
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
value <- "Library"
cat(sub("[0-9]+", "*", value), "\n", sep = "")
Library
With no digit match the label stays the same.
Mask a public job number
A noticeboard shows the department prefix and hides the serial. The editor replaces a matching run of digits with a single star before sharing the label. Each sample has one numeric run.
What to watch for
Replacement syntax differs between regex engines. Use a literal replacement when punctuation must be matched exactly.