Search code examples
stringgoreplaceescaping

How to replace "\" with an empty string?


Hi im trying to replace this specific character from an entire string in go but i get the

missing ',' in argument list

This is my code, as you can see im using the strings.Replace function but it looks like "/" is too much for it to handle.

loadPAConfigurationData.Data = strings.Replace(loadPAConfigurationData.Data, "u003E", ">", -1)
loadPAConfigurationData.Data = strings.Replace(loadPAConfigurationData.Data, "u003C", "<", -1)
loadPAConfigurationData.Data = strings.Replace(loadPAConfigurationData.Data, "\r\n", "", -1)
loadPAConfigurationData.Data = strings.Replace(loadPAConfigurationData.Data, "\", "", -1)

Im only getting the error in the last line. Any help please?


Solution

  • The part of the statement with the call

    strings.Replace(loadPAConfigurationData.Data, "\", "", -1)
    

    gets parsed as follows.

    Since \" is a so-called escape sequence allowing for the double quote character to appear in a double-quoted string literal, the Go parser reads the first " which starts a string literal, then it reads \" which is treated as ", then it reads the , followed by a space, and then sees another " which ends the string literal. At this point the parser has collected another–the second–argument to the method call being parsed.

    The parser starts to scan further, expecting to see another argument to the function call, and finds another " while it expected to find either a ), or a comma (possibly with some whitespace before them) which separates the arguments to a call. The parser stops and reports an error.

    In other words, that's what the parser sees:

                                                        +- expected a , or a )
                                                        |
                                                        v
    strings.Replace(loadPAConfigurationData.Data, "\", "", -1)
    ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ^^^^^^
    |               |                             |
    |               |                             +- the second argument
    |               +- the first argument
    +- the method to call
    

    As to solving the problem, you probably wanted to use

    "\\"
    

    or

    `\`
    

    to represent a string consisting of a sole double quote character.

    This is explained in the docs but your question is so basic I recommend to take your time and complete at least some introductory material on Go. You migth start with The Go Tour.