cohen
String.replace and escaping weirdness
I have some code that finds all instances of the characters , %, and _, inserting a backslash in front of them to escape them in the resulting SQL string. I’m a little bit confused about the amount of \ characters I need to use to do this. I would think that String.replace(string, ~r/([\\%_])/, "\\\\1") would do it, since I put in "\\" for a single backslash, then "\\1" for the backslash-one syntax to get my first capture. However, this results in substituting the characters backslash and 1, e.g., a_b → a\1b (on IO.puts).
It seems like this because "\\\\1" is the intended syntax for substituting an actual, literal backslash and "\\\\\\1" does the trick, but to be honest I’'m confused about how the escaping is actually working in this case.
Does anyone have any insights?
Most Liked
NobbZ
In the replacement language \ has a special meaning. So if you want it literally, you need to escape it.
Your string \\\\1 is seen by the replacement language as \\1, which will result in the replace of \1 (as printed) or \\1 (as inspected).
To actually get a single backslash followed by the content of the capture, you need 3 backslashes followed by a one in the replacement language, which in a string literall have to be doubled, such that you end up with 6 of them.
When I do write replacments, I usually use ~S to avoid the duplication, then I can do ~S"\\\1".
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









