Skip to content
Prev 175289 / 398506 Next

text matching and substitution

Stephan Kolassa wrote:
if you have a fixed collection of strings (here, colour names) that you
want to recognize within a string and use as a replacement, here's one
other way to do it:

    # some dummy data ...
    colors = sample(colors(), 10)
    data = replicate(10,
       paste(sep=' ',
          paste(sample(letters, sample(10, 1)), collapse=''),
          sample(colors, 1),
          paste(sample(letters, sample(10, 1)), collapse='')))

    # ... and the actual solution
    output = sub(perl=TRUE,
        x=data,
        pattern=sprintf('.*?(%s).*', paste(colors, collapse='|')),
        replacement='\\1')

this will solve the problem as you state it.

vQ