[R] Regex exercise

Thomas Lumley tlumley at u.washington.edu
Fri Aug 20 23:33:01 CEST 2010


On Fri, 20 Aug 2010, Bert Gunter wrote:

> Given the string (entered, say, at a readline prompt):
>
> "1   2 -5, 3- 6 4  8 5-7 10"   ## only integers will be entered

Presumably only non-negative integers

> (Special note to Thomas Lumley: This seems one of the few instances
> where eval(parse..)) may actually be appropriate.)
>

Yes, implementing a new minilanguage is a valid use.  It isn't necessary, and the following could probably be improved on

s<-"1   2 -5, 3- 6 4  8 5-7 10"

npos<-gregexpr("[0-9]+",s)[[1]]
numbers<-as.numeric(substring(s,npos,attr(npos,"match.length")+npos-1))
hyphens<-findInterval(gregexpr("-",s)[[1]],npos)
nn<-as.list(numbers)
nn[hyphens+1]<-mapply(seq,numbers[hyphens]+1,numbers[hyphens+1])
unlist(nn)


      -thomas

Thomas Lumley
Professor of Biostatistics
University of Washington, Seattle


More information about the R-help mailing list