[R] regular expression

Gabor Grothendieck ggrothendieck at gmail.com
Sun Apr 8 14:08:21 CEST 2007


Your example is a vector of strings not a string with mulitple lines.
To turn it into a string with mulitple lines use paste:

gsubfn('["][^"]*["]', f, paste(Lines, collapse = "\n"))

If you want to break up the output to create a vector
of strings rather than a single multi-line string see
?strsplit

On 4/8/07, Laurent Rhelp <laurentRhelp at free.fr> wrote:
> Gabor Grothendieck a écrit :
>
> >On 4/7/07, Laurent Rhelp <laurentRhelp at free.fr> wrote:
> >
> >
> >>Gabor Grothendieck a écrit :
> >>
> >>
> >>
> >>>I assume is to replace single quotes in double quoted strings with single quoted
> >>>strings containing double quotes in place of the single quotes
> >>>
> >>>
> >>>
> >>that's rignt
> >>
> >>
> >>
> >>>while leaving
> >>>double quoted strings not containing single quotes as they are (i.e. leave them
> >>>as double quoted).
> >>>
> >>>
> >>>
> >>No, at the end,  I have to replace all the double quotes (") by simple
> >>quote (')
> >>
> >>
> >
> >In that case it simplifies to the following (same as before except
> >for definition of f):
> >
> >library(gsubfn)
> >
> >squote <- "'" # single quote. This is a double quote, single quote, double quote
> >dquote <- '"' # double quote  This is a single quote, double quote, single quote
> >
> >s <- "[\"...\" \"...'...\"]"
> >f <- function(x)  chartr(paste(squote, dquote), paste(dquote, squote), x)
> >gsubfn('["][^"]*["]', f, s)  #   "['...' '...\"...']"
> >
> >______________________________________________
> >R-help at stat.math.ethz.ch mailing list
> >https://stat.ethz.ch/mailman/listinfo/r-help
> >PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> >and provide commented, minimal, self-contained, reproducible code.
> >
> >
> >
> >
>
> I discovered that it doesn't work when the pattern "...." is not on one
> line.
> Here's an example of file read with readLines :
>
> Lines <- c("line one example",
> "line two example",
> "example \"comment on one line it works \" end of the line",
> "example \" comment on two lines",
> "the end of the comment \" without ' inside",
> "example \" comment on one line with ' inside it works \" end of the line",
> "example \" comment on two lines with '",
> "inside it doesn't works \"")
>
> s <- Lines
> f <- function(x)  chartr(paste(squote, dquote), paste(dquote, squote), x)
> gsubfn('["][^"]*["]', f, s)
>
> [1] "line one
> example"
> [2] "line two
> example"
> [3] "example 'comment on one line it works ' end of the
> line"
> [4] "example \" comment on two
> lines"
> [5] "the end of the comment \" without '
> inside"
> [6] "example ' comment on one line with \" inside it works ' end of the
> line"
> [7] "example \" comment on two lines with
> '"
> [8] "inside it doesn't works \""
>
>
>
>
>



More information about the R-help mailing list