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

时间:2010-11-24 10:48:53

标签: ruby

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

4 个答案:

答案 0 :(得分:11)

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

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。测试单位证明它有效:

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

答案 1 :(得分:3)

由于评估,更短,更黑,更危险:

eval "\"#{string}\""
一个简单的例子:
> a = '1\t2\n3'
> puts a
1\t2\n3
> puts eval "\"#{a}\""
1       2
3

答案 2 :(得分:1)

以下代码将正确解码ISO-C标准定义的所有转义序列。它节省且性能合理:

ISO_C_ESCAPE_SEQUENCES = %r{
    # One letter escapes
    (?:\\[abfnrtv\\'"?])

    # Hex encoded character
    | (?:\\(x)([A-Fa-f0-9]{2,}))

    # Any Unicode code point (8 hex digits) or
    # Unicode code point below 1000 (4 hex digits)
    | (?:\\(u)((?:[A-Fa-f0-9]{8})|(?:[A-Fa-f0-9]{4})))

    # Octal encoded character
    | (?:\\([0-7]{1,3}))
}x


ISO_C_ONE_LETTER_ESCAPES = {
    "\\a"  => "\a",
    "\\b"  => "\b",
    "\\f"  => "\f",
    "\\n"  => "\n",
    "\\r"  => "\r",
    "\\t"  => "\t",
    "\\v"  => "\v",
    "\\\\" => "\\",
    "\\'"  => "'",
    "\\\"" => "\"",
    "\\?"  => "?"
}


def decodeCString( cString )
    return cString.gsub(ISO_C_ESCAPE_SEQUENCES) { |match|
        replacement = ISO_C_ONE_LETTER_ESCAPES[match]
        next replacement if replacement
        next $2.to_i(16).chr if $1 == "x"
        next $4.to_i(16).chr(Encoding::UTF_8) if $3 == "u"
        next $5.to_i(8).chr
    }
end

这里是一个示例:

puts decodeCString("Line \\\\n Same Line!\\nNew line\\x0ANew line")
puts decodeCString("Smiley: \\u263A\tHorse head: \\u00010083")
puts decodeCString("Equal sign in quotes: \\\"\\75\\\"")

打印

Line \n Same Line!
New line
New line
Smiley: ☺   Horse head: ?
Equal sign in quotes: "="

答案 3 :(得分:0)

编辑:请注意,这实际上不起作用。你真的需要在这里建立一个适当的解析器,状态机跟踪你是否在转义序列中。


Ruby支持许多相同的转义序列,因此您可以构建一个简单的转换表:

T = {
  '\n' => "\n",
  '\t' => "\t",
  '\r' => "\r"
}

然后使用该转换表替换源字符串中的那些序列:

a = '1\t2\n3'

a.gsub(/#{T.keys.map(&Regexp.method(:escape)).join('|')}/, &T.method(:[]))
# => "1\t2\n3"