Regex Extraction and Replacement Helpers in Base R
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement four vectorized text helpers using base R regex (`gsub`, `regmatches`, `regexpr` or `gregexpr`). Each takes a character vector, returns a result of the same length, and handles empty strings gracefully.
- `extract_first_email(text)`: a character vector holding the first match of `[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}` in each string, or `NA_character_`.
- `extract_all_numbers(text)`: a list where element i holds every number (integer or decimal, such as `3` or `12.5`) in `text[i]`, in order, converted with `as.numeric`, or `numeric(0)`.
- `redact_phone(text)`: replace every match of `\d{3}-\d{3}-\d{4}` with `"[PHONE]"` and leave other text unchanged.
- `normalize_whitespace(text)`: collapse each run of whitespace to one space and trim both ends.
Example:
```r
extract_first_email(c("contact a@x.com or b@y.io", "none here"))
#> c("a@x.com", NA)
extract_all_numbers(c("buy 3 for 12.5", "nope"))
#> list(c(3, 12.5), numeric(0))
redact_phone("call 555-123-4567 now")
#> "call [PHONE] now"
normalize_whitespace(" hi there \t world ")
#> "hi there world"
```
```hint First match or every match
Base R has one function that locates the first match in each string and another that locates all of them. Check what `regmatches()` gives back with each one when some strings have no match at all.
```
```hint Test the awkward inputs
Run each helper on `c("", "no digits here", "buy 3 for 12.5")` before you trust it. Watch the length of the result and whether `12.5` stays one number.
```
### Constraints & Assumptions
- Base R only, no extra packages.
- `text` is a character vector of any length and may contain empty strings.
### What a Strong Answer Covers
- Uses `regexpr` for the first email and `gregexpr` for all numbers, with `regmatches` to extract the matched text.
- Keeps every output aligned with the input: `NA_character_` where no email is found and `numeric(0)` where a string has no number.
- Uses a number pattern that keeps the decimal part attached to the integer part, and converts the matches with `as.numeric`.
- Uses global substitution for redaction and whitespace collapsing, and trims both ends.
- Handles empty strings and a zero-length input vector without errors.
### Follow-up Questions
- How would you support international phone formats in `redact_phone`?
- Why prefer `regmatches` with `gregexpr` over splitting strings manually?
- `extract_all_numbers("-4 degrees")` returns `4`. How would you keep the sign, and what new false matches could that create?
Overview: Write four vectorized base R helpers that pull the first email out of each string, extract every number, redact phone numbers, and normalize whitespace. It tests choosing between first-match and all-match regex functions and keeping output aligned with the input when a string has no match.