1

I'm writting a ruby-on-rails application that fills latex formulars. Now I run into an pdflatex error when a user filed variable includes the character & (e.g., Company & Co. KG). For latex it is a new table column and I need to escape these characters with \&.

I'm using Rails 5.2.3 with ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu] on Ubuntu 18.04.3 LTS.

I've tried using gsub to replace all & in a string but ran into two problems.

  1. \& is replaced by the matched string
  2. I can only insert a double backslash \\

So I also tried replace the character before a & with a \ with no success.

a = "T & T"
a.gsub(&, "\&")               -> "T & T"
a.gsub(/(.{1})(?=&)/, " \")   -> error:  unterminated string meets end of file
a.gsub(/(.{1})(?=&)/, " \\")  -> "T \\& T" 

How can I replace a character with a single \ or can I escape the reversed \& somehow?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • 1
    You are most likely inspecting your string in a way that shows you the escaped version. Try this in irb: `92.chr` (which produces a string with a single slash) will output `"\\"`; but `puts 92.chr` will produce `\ `, the true content of the string. None of your code is giving you double backslashes. – Amadan Sep 06 '19 at 06:08
  • Do you want to replace "&" and " " both ? or just "&" with space? – Vishal Sep 06 '19 at 06:13
  • 1
    What if your `&` is already escaped? You will have two backslashes before the `&` if you use `.gsub('&', '\\\&')`. Use `.gsub(/\\?&/, '\\\&')`. – Wiktor Stribiżew Sep 06 '19 at 06:52

1 Answers1

1

Use triple \ in the replacement string:

print 'Company & Co. KG'.gsub('&', '\\\&')
# Company \& Co. KG=> nil

You can check that a single backslash is added by checking the length of both strings:

'Company & Co. KG'.size
# => 16
'Company & Co. KG'.gsub('&', '\\\&').size
# => 17

To understand it better, read about escaping:

EDIT:

\& is a backreference to the whole match (like \0)

'Company & Co. KG'.gsub(/Co/, '-\&-')
# => "-Co-mpany & -Co-. KG"
'Company & Co. KG'.gsub(/Co/, '-\0-')
# => "-Co-mpany & -Co-. KG"

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • Thanks, but it is not working. When I run this I get ```>> 'Company & Co. KG'.gsub('&', '\\\&') => "Company \\& Co. KG"``` – JonnyTischbein Sep 06 '19 at 06:11
  • 1
    Read my comment under the question. There are _not_ two backslashes in the result, despite the appearances. This answer is correct. – Amadan Sep 06 '19 at 06:12
  • Is there a way to esacpe the `\&` ? I ran into further problems because the actual filling of my tex file is done again by gsub which reads the `\&` as `\0` as you stated. Edit: The solutions in your link don't work for me – JonnyTischbein Sep 06 '19 at 06:26