R: Replace matched substrings with new text

ore.subst {ore} | R Documentation

## Replace matched substrings with new text

### Description

This function substitutes new text into strings in regions that match a regular expression. The substitutions may be simple text, may include references to matched subgroups, or may be created by an R function.

### Usage

    ore.subst(regex, replacement, text, ..., all = FALSE)

### Arguments

`regex` | A single character string or object of class `"ore"`. In the former case, this will first be passed through `ore`.
`replacement` | A single character string, or a function to be applied to the matches.
`text` | A vector of strings to match against.
`...` | Further arguments to `replacement`, if it is a function.
`all` | If `TRUE`, then all matches within each element of `text` will be found. Otherwise, the search will stop at the first match.

### Details

If `replacement` is a function, then it will be passed as its first argument an object of class `"orearg"`. This is a character vector containing as its elements the matched substrings, and with an attribute containing the matches for parenthesised subgroups, if there are any. A `groups` method is available for this class, so the groups attribute can be easily obtained that way. The substitution function will be called once per element of `text`.

### Value

A version of `text` with the substitutions made.

### See Also

`ore.search`

### Examples

    # Simple text substitution (produces "no dogs")
    ore.subst("\\d+", "no", "2 dogs")

    # Back-referenced substitution (produces "22 dogs")
    ore.subst("(\\d+)", "\\1\\1", "2 dogs")

    # Function-based substitution (produces "4 dogs")
    ore.subst("\\d+", function(i) as.numeric(i)^2, "2 dogs")

[Package ore version 1.6.0 Index]