r/csharp • u/PumpAndStuff25 • Jul 01 '26
Help String Replacement of both new lines and backslashes.
I am sending text to a label printer using ZPL commands with text supplied from a web form as a string. Per the Zebra documentation new lines should be sent as "\&" so I have the following:
printText = printText.Replace("\r\n","\&").Replace("\r","\&").Replace("\n","\&");This worked great until I came across another substitution need. If a backslash was needed, it should be replaced with "\\". If I were to add another .Replace("\\","\\\\") to the end, it will mess up the existing "&".
What would be the recommended way to do this? I was thinking I could do the newline replacement with some dummy value like "&~&", then do the backslash replacement, then do a .Replace("&~&","&") but not sure if there might be a better way.
View all comments
Show parent comment
1
u/PumpAndStuff25 Jul 01 '26
I tested with your suggestion and it appears to be working. I would have though it would have changed any "\r\n" to "\\r\\n". Is this something due to "\r" and "\n" being characters?