---
title: "Extractions and Replacements"
author: "Statistical Computing, 36-350"
date: "Wednesday September 14, 2016"
---

Extracting matching substrings
===

To get the specific substring that matches a regex pattern (rather than a whole line of matched text), use `regexpr()` and `regmatches()`

- `regexpr()` returns location of first match in the target string (plus some attributes)
- A location of `-1` means no match was found in the target string
- `regmatches()` takes the output of `regexpr()`, and teturns the matching substring

Examples
===

```{r}
str.vec.1 = c("O my gosh!", "Oh wow!", "Ohhhhh no!")
grep("Oh+", str.vec.1, value=TRUE)
regexpr.1 = regexpr("Oh+", c("O my gosh!", "Oh wow!", "Ohhhhh no!"))
class(regexpr.1) # Integer vector
regexpr.1 # Position of match
attributes(regexpr.1)$match.length # Length of match
regmatches(str.vec.1, regexpr.1)
```

More examples
===

```{r}
str.vec.2 = c("10 dollars", "100 dollars", "1000 dollars")
grep("10{1,2}", str.vec.2, value=TRUE)
grep("10{1,}", str.vec.2, value=TRUE)
regmatches(str.vec.2, regexpr("10{1,2}", str.vec.2))
regmatches(str.vec.2, regexpr("10{1,}", str.vec.2))
```

Replacing matching substrings
===

To replace matching substrings, use `regmatches()` (similar to usage of `substring()`)

```{r}
str.vec.1
regmatches(str.vec.1, regexpr("Oh*", str.vec.1))
regmatches(str.vec.1, regexpr("Oh*", str.vec.1)) = "Oh"
str.vec.1
```

More examples
===

```{r}
str.vec.3 = c("I hate broccoli", "I HATE BROCCOLI",
              "I hate hate HATE HATE broccoli, it disgusts me, I hate it")
pattern.3 = "(hate|HATE)( (hate|HATE))*"
regmatches(str.vec.3, regexpr(pattern.3, str.vec.3)) = "do not like"
str.vec.3
```

Note: in the 3rd string, we didn't replace the last "hate", why?

Extracting all occurrences
===

To extract all occurrences of matching substrings (not just the first occurrence per line), use `gregexpr()` and then `regmatches()`

```{r}
str.vec.3 = c("I hate broccoli", "I HATE BROCCOLI",
              "I hate hate HATE HATE broccoli, it disgusts me, I hate it")
regexpr("hate|HATE", str.vec.3) # Integer vector
gregexpr("hate|HATE", str.vec.3) # List of integer vectors
regmatches(str.vec.3, regexpr("hate|HATE", str.vec.3))
regmatches(str.vec.3, gregexpr("hate|HATE", str.vec.3))
```

More examples
===

```{r}
str.vec.3
pattern.3
regmatches(str.vec.3, gregexpr(pattern.3, str.vec.3)) = "do not like"
str.vec.3
```

Replacements, alternative way
===

For an alternative (easier) way to replace matching substrings, use `sub()` or `gsub()`

- `sub()` replaces the first occurrence of a matching substring
- `gsub()` replaces all occurrences of matching substrings

```{r}
str.vec.3 = c("I hate broccoli", "I HATE BROCCOLI",
              "I hate hate HATE HATE broccoli, it disgusts me, I hate it")
pattern.3
gsub(pattern.3, "do not like", str.vec.3)
```
