R regexpr
Locate the first separator or search term in a plain ASCII record.
A simple example
regexpr
- Start with "aba", looking for b
- Do this Find the first match
- Result Position 2 (one-based)
value <- "aba"
other <- "b"
cat(as.integer(regexpr(other, value, fixed = TRUE)), "\n", sep = "")
2
Syntax
as.integer(regexpr(other, value, fixed = TRUE))
Run these examples in R
Save one example at a time as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.RLocate the hyphen in a classroom code
A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.
value <- "CS-104"
other <- "-"
cat(as.integer(regexpr(other, value, fixed = TRUE)), "\n", sep = "")
3
The hyphen follows the two letters CS. R counts positions from one.
Find the first separator on a route
A route string contains several stops separated by the same punctuation. Find the first separator to locate the end of the starting stop before the remaining route is processed.
value <- "A/B/C"
other <- "/"
cat(as.integer(regexpr(other, value, fixed = TRUE)), "\n", sep = "")
2
The first slash comes immediately after A. R counts positions from one.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
Check the language-specific missing-match result before slicing. Byte and character offsets may diverge for Unicode input.