0

I would like to find and replace tabular instances by tabularx. I tried with gsub but it seems to enter me into a world of escaping pain. Following other questions and answers I find fixed=TRUE which is the best I so far have. The code snippet below almost works, \B is unrecognized. If I escape it twice I get \BEGIN as output!

texText <- '\begin{tabular}{rl}\begin{tabular}{rll}'

texText <- gsub("\begin{tabular}{rl}", "\BEGIN{tabular}{rll}", texText, fixed=TRUE)

I'm using BEGIN as my test to see what is happening. This is before I get to tackling the question of what goes on in the brackets {rl} {ll} {rrl} etc. Ideally I'm looking for a regex that would output:

\begin{tabularx}{rX}\begin{tabularx}{rlX}

That is the final column is replaced by X.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Geoff
  • 925
  • 4
  • 14
  • 36
  • `'\\B'` is ``\B`` text. You can easily see that with `cat('\\B')`. **To define a literal backslash, it must be doubled**, `'\\'`. BTW, `fixed=TRUE` triggers fixed, non-regex, search and replace. – Wiktor Stribiżew Apr 21 '21 at 16:34

1 Answers1

1

Try using proper escaping:

texText <- "\begin{tabular}{rl}\begin{tabular}{rll}"
output <- gsub("\begin\\{tabular\\}", "\begin{tabularx}", texText)
output

[1] "\begin{tabularx}{rl}\begin{tabularx}{rll}"

A literal backslash requires two backslashes, and also metacharacters such as { and } require two backslashes.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360