Converting triples slashes, to single slashes?

"data-id=\"\\\"6254338\\\"\""

Given this string, how could I convert the triple slashes to single slashes?

I tried:

"data-id=\"\\\"6254338\\\"\"" 
|> String.replace("\\\\\\", "\\")`

But no dice…

Maybe this?

iex(1)> s = "data-id=\"\\\"6254338\\\"\""
"data-id=\"\\\"6254338\\\"\""
iex(2)> Regex.replace(~r/\\/, s, "")     
"data-id=\"\"6254338\"\""

# or

iex(3)> String.replace(s, "\\", "")  
"data-id=\"\"6254338\"\""

Here is your subject: "data-id=\"\\\"6254338\\\"\"".

Firstly we can remove " character at start and end for simplify: data-id=\"\\\"6254338\\\"\".

Now let’s describe it part by part:

  1. data-id= is raw data
  2. \"\\\" means escape ", \ and " characters
  3. 6254338 is raw data
  4. \\\"\" means escape \, " and " characters

Now your pattern: \\\\\\ means escape: \, \ and \ characters one after other. Look that nowhere you have 3 times \ character escaped, so your code would just never work as expected.

Here are some code examples:

subject = "data-id=\"\\\"6254338\\\"\""
# 1st - remove only escaped \ character:
String.replace(subject, "\\", "")  
"data-id=\"\"6254338\"\""

# 2nd - remove escaped \" characters:
String.replace(subject, "\\\"", "")
"data-id=\"6254338\""

# 3rd - remove all escaped characters:
String.replace(subject, ["\\", "\""], "")
"data-id=6254338"

Looks like 1st example is what you are trying to achieve.

Note: If possible try to avoid using Regular Expressions as they are much slower than other solutions like for example pattern matching.

3 Likes

With strings that themselves contain a lot of ", or regular expressions that contain a lot of /, the sigils (in this case, sigil_s and sigil_r that Elixir offers become an attractive alternative to make the things more readable.

1 Like

It works - but I think the code (and the topic title) focuses on the wrong thing.

The problem presented actually seems to be:

  • wherever there is \\\", I need \"

i.e.
String.replace(subject, "\\\"", "\"")

1 Like

Yup, I was also not sure about this. It’s mainly why I described how it could be solved and I gave few more examples in case there is any misunderstanding. Please notice that I wrote: Looks like (…) which means that I was not sure what exactly author of this topic was looking for. As you said I directly followed description, but in my opinion it’s what every developer should do i.e. do not try to understand everything on my own way and just do what author wrote. Anyway depends on use case all my 3 examples are in some way useful. By describing I wanted to help understanding of escaping behavior using backslash (\) character.

1 Like