0

I have strings in an array:

["foo","bar","foo"bar"baz"]

I am using eval method to form an array with this string, but the inner double quotes are not escaped:

eval('["foo","bar","foo"bar"baz"]') # => SyntaxError

Is there a way to escape only the ones inside an array element?

8
  • Have you tried to write a pattern for that? Please share your attempt(s). Commented Jul 20, 2016 at 8:03
  • Could you tell, what you want to get as a result? Commented Jul 20, 2016 at 8:06
  • @WiktorStribiżew I am trying this repl.it/CdvP/1 Commented Jul 20, 2016 at 8:10
  • 2
    @SergeyGuide something that i can use in eval to create a ruby array ["foo","bar","foo\"bar\"baz"] Commented Jul 20, 2016 at 8:11
  • so did you try the backslash? Commented Jul 20, 2016 at 8:12

2 Answers 2

3

I think you can try something like

eval('["foo","bar","foo"bar"baz"]'.gsub(/(\w)\"(\w)/, '\1\"\2'))

if I got what you have meant

Sign up to request clarification or add additional context in comments.

13 Comments

Or .gsub(/\b"\b/,'\"')
Yeah, this is much more elegant solution
I think it won't fix all the cases, unfortunately. What about '["foo","foo"b ar"baz",""an"t"on""]'?
Thanks @SergeyGuide
@WiktorStribiżew Thanks for your solution and I am testing with eval('["foo","bar","foo "bar" baz"]'.gsub(/\b"\b/,'\"')) and it is not working. Both of the solutions, unfortunately.
|
1

This might work for all possible variants. This would fix all quotes except of appearing near commas and brackets

.gsub(/(?<!\,)(?<!\[)(?<!\])\"(?!\,)(?!\[)(?!\])/, '\"')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.