R — Finding delimiters and trimming text
In R, regexpr finds the first position of a delimiter or reports that it is missing. Use the position to separate the two fields before trimming them.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
parts <- strsplit("a=b", "=", fixed = TRUE)[[1]]
cat(parts[2])
b
Split one setting into a key and a value
regexpr reports the first match using one-based positions. A negative result means no separator was found. trimws removes whitespace from the two extracted substrings.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
record <- " city = Lima "
split_at <- regexpr("=", record, fixed = TRUE)[1]
if (split_at > 0) {
key <- trimws(substr(record, 1, split_at - 1))
value <- trimws(substring(record, split_at + 1))
cat(key, "=", value, "\n", sep = "")
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.