Lesson contents

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

  1. Start with "a=b"
  2. Do this Separate at =
  3. Result b
The separator marks where the first field ends and the second begins. Read the second field.
Lesson.R
parts <- strsplit("a=b", "=", fixed = TRUE)[[1]]
cat(parts[2])
Output
b
Advertisements

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.

Saved line: city = Lima. Setting name: city. Display value: Lima.
Read a destination from a settings file

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
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 = "")
}
Output
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.

An Introduction to R

Related tags

  • R
  • strings
  • parsing
  • whitespace