문제

What is the simplest way to unescape the following string in Ruby.

Sample Input

str = "\\u003Cul id=\\\"list_example\\\"\\u003E\\n\\t\\u003Cli class=\\\"item_example\\\"\\u003EHello\\u003C/li\\u003E\\n\\u003C/ul\\u003E\\n\\n"
puts str # => \u003Cul id=\"list_example\"\u003E\n\t\u003Cli class=\"item_example\"\u003EHello\u003C/li\u003E\n\u003C/ul\u003E\n\n
str.encoding # => #<Encoding:UTF-8>

Desired Output

puts str #=>
<ul id="list_example">
  <li class="item_example">Hello</li>
</ul>
도움이 되었습니까?

해결책

That string is escaped twice. There are a few ways to unescape it. The easiest is eval, though it is not safe if you don't trust the input. However if you're sure this is a string encoded by ruby:

print eval(str)

Safer:

print YAML.load(%Q(---\n"#{str}"\n))

If it was a string escaped by javascript:

print JSON.load(%Q("#{str}"))

See also Best way to escape and unescape strings in Ruby?

다른 팁

The simplest approach is just to read the string as a JSON string.

unescaped_str = JSON.load("\"#{str}\"")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top