如何从 ruby​​ 中取消转义 c 风格的转义序列?

编程入门 行业动态 更新时间:2024-10-13 20:19:34
本文介绍了如何从 ruby​​ 中取消转义 c 风格的转义序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 ruby​​ 中,我如何解码 c 风格的转义序列?例如'\n' 到换行符,'\t' 到制表符?

In ruby, how do I decode c-style escape sequences? e.g. '\n' to a newline, '\t' to a tab?

推荐答案

好吧,如果你不喜欢 eval 解决方案,我已经在 Ruby 中破解了一个简单的状态机来解析简单的\n" 和 "\t" 在字符串中正确,包括反斜杠本身的预转义.这是:

Okay, if you don't like eval solution, I've hacked a simple state machine in Ruby to parse simple "\n" and "\t" in strings correctly, including pre-escaping of backslash itself. Here it is:

BACKSLASH = "\\" def unescape_c_string(s) state = 0 res = '' s.each_char { |c| case state when 0 case c when BACKSLASH then state = 1 else res << c end when 1 case c when 'n' then res << "\n"; state = 0 when 't' then res << "\t"; state = 0 when BACKSLASH then res << BACKSLASH; state = 0 else res << BACKSLASH; res << c; state = 0 end end } return res end

这个可以轻松扩展以支持更多字符,包括多字符实体,例如 \123.测试单元以证明其有效:

This one can be easily extended to support more characters, including multi-character entities, like \123. Test unit to prove that it works:

require 'test/unit' class TestEscapeCString < Test::Unit::TestCase def test_1 assert_equal("abc\nasd", unescape_c_string('abc\nasd')) end def test_2 assert_equal("abc\tasd", unescape_c_string('abc\tasd')) end def test_3 assert_equal("abc\\asd", unescape_c_string('abc' + BACKSLASH * 2 + 'asd')) end def test_4 assert_equal("abc\\nasd", unescape_c_string('abc' + BACKSLASH * 2 + 'nasd')) end def test_5 assert_equal("abc\\\nasd", unescape_c_string('abc' + BACKSLASH * 3 + 'nasd')) end def test_6 assert_equal("abc\\\\nasd", unescape_c_string('abc' + BACKSLASH * 4 + 'nasd')) end end

更多推荐

如何从 ruby​​ 中取消转义 c 风格的转义序列?

本文发布于:2023-10-08 15:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1472979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   风格   ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!