[R] Doubt about pattern

Martin Maechler maechler at stat.math.ethz.ch
Fri Jan 30 19:11:28 CET 2004


>>>>> "Gabor" == Gabor Grothendieck <ggrothendieck at myway.com>
>>>>>     on Fri, 30 Jan 2004 08:56:59 -0500 (EST) writes:

    Gabor> Your question has by now been answered but I thought
    Gabor> I would add that if you want to do it via file globbing on Windows
    Gabor> rather than regular expressions then this function would help:


    Gabor> list.files.glob <- function( spec ) {
    Gabor> # returns list of files or NULL if none: spec uses globbing and can
    Gabor> # use either forward or backward slashes. 
    Gabor> # e.g list.files.glob( "c:/a*.*" )
    Gabor> # e.g. list.files.glob( "c:/myfolder/my*.dat")
	     =====================
    Gabor> # only works on Windows
	     =====================
    Gabor> if ( substring(spec,2,2) != ":" ) spec <- paste( "C", spec, sep= ":" )
    Gabor> z <- system( paste("cmd /c attrib", spec), intern = T, invisible = T)
    Gabor> if ( !pmatch("File not found - ", z[1], nomatch = 0) )  substring(z,12)
    Gabor> }


    Gabor> For example:

    Gabor> list.files.glob( "*.sens" )

Since we are diverting, here is my 12 year old (back then, 
  using "unix(..)" and 'sed' inside Unix all for S-plus)
"solution" to this problem -- yes, the function _name_ is a misnomer --

which is platform independent

pat2grep <- function(pattern)
{
  ## Purpose: Change "ls" aka "wildcard" aka "globbing" _pattern_ to
  ## 	      Regular Expression (as in grep, perl, emacs, ...)
  ## -------------------------------------------------------------------------
  ## Author: Martin Maechler ETH Zurich, ~ 1991
  ##         New version using [g]sub() : 2004
    p <- gsub('\\.','\\\\.', paste('^', pattern, '$', sep=''))
    sub('\\.\\*\\$$','', gsub('\\?',  '.',  gsub('\\*',  '.*', p)))
}


and now you can use, e.g.

  list.files(pat2grep("*.R")) 

and get what you expect.
Beginners in regular expressions
now can also use

  pat2grep( <my favorite wildcard expression> )

and see the correct (I hope; the tests were not realy extended)
regular expression for this.

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><




More information about the R-help mailing list