0

I am not an expert on Regex in R, but I feel I have read the docs first long enough and still come up short, so I am posting here.

I am trying to replace the following string, all LITERALLY as written:

a = "\\begin{tabular}"
a = gsub("\\begin{tabular}", "\\scalebox{0.7}{
\\begin{tabular}", a)

Desired output is : cat('\\scalebox{0.7}{ \\begin{tabular}')

So I know I need to escape the first "\" to "\", but when I escape the brackets I get

Error: '\}' is an unrecognized escape in character string starting...
wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90
  • I think you might need your example input to be `a = "\\begin{tabular}"` - otherwise it won't contain a literal "\begin" – Marius Mar 29 '19 at 03:35
  • Fixed that, sorry! – wolfsatthedoor Mar 29 '19 at 03:37
  • 1
    not sure if this is what you need? `cat(sub("\\begin{tabular}", "\\scalebox{0.7}{\\begin{tabular}", a, fixed = TRUE))` ? – Ronak Shah Mar 29 '19 at 03:51
  • 2
    `cat(gsub("\\\\begin\\{tabular\\}", "\\\\scalebox{0.7}{\\\\begin{tabular}", a))` – d.b Mar 29 '19 at 03:51
  • Wow, can you explain that? – wolfsatthedoor Mar 29 '19 at 03:57
  • I am also curious to see if there's some documentation explaining why curly brackets have to be escaped in `pattern` but not the `replacement` of `gsub` – d.b Mar 29 '19 at 04:54
  • @d.b curly braces have a special meaning in a regular expression which is what you are passing as the first parameter to `gsub`, but the second parameter of `gsub()` is not a regular expression so you don't need the same kind of escaping. – MrFlick Mar 29 '19 at 05:33
  • 1
    @MrFlick, that makes sense. If the `pattern` takes regular expression, that explains why we need four back slashes for literal '\' too. But why do we need four back slash for one '\' in `replacement` if that is not regular expression. – d.b Mar 29 '19 at 15:42

1 Answers1

0

In your case since you're seeking to replace a fixed string, you can simply set fixed = T option to avoid regular expressions entirely.

a = "\\begin{tabular}"
a = gsub("\\begin{tabular}", "\\scalebox{0.7}{\n\\begin{tabular}", x=a, fixed= T)

and use \n for the newline.

If you did want to use regex, you need to escape curly bracket in pattern using two backslashes rather than one.

e.g.,

a = "\\begin{tabular}"

gsub(pattern = "\\{|\\}", replacement = "_foo_", x=a)

[1] "\\begin_foo_tabular_foo_"

Alternatively, you can enclose the curly brackets in square brackets like so:

e.g.,

a = "\\begin{tabular}"

gsub(pattern = "[{]|[}]", replacement = "_foo_", x=a)

[1] "\\begin_foo_tabular_foo_"
Brian D
  • 2,570
  • 1
  • 24
  • 43