Home>

I want to convert Chinese numerals to alphanumeric characters using ruby, but I'm having trouble.

I want to make Chinese numerals other than "Chinese numerals + number" alphanumeric
〇 1 2 3 4 5 6 7 8 9 respectively
〇 to 0
I want to change one to one.

With the code below,
I am in trouble because the display becomes [0-9]

buffer = f.read ()
p buffer
buffer.gsub! (/ [01 2 3445 6789] (?!) /,'[0-9]');


The site I referred to isHow to convert Chinese numerals to numbers with ruby ​​I think this is probably the easiest ()
is.
Because there are some parts in the text where I want to keep the Chinese numerals and some parts I want to convert.
I'm in trouble because I can't do it well.

I know it's a rudimentary question,
I would be grateful if anyone could teach me.

  • Answer # 1

    buffer.gsub! (/ ([01 2 3 4 5 6 7 8 9]) (?!) /) {$1.tr ("01 2 3 4 5 6789", '0-9' )}
    How about?

  • Answer # 2

    If you don't have to think about ten or picking up, tr is easy
    "01 2 3 4 5 6 7 8 9" .tr (" 0 1 2 3 4 5 6 789", '0-9') =>"0123456789"

  • Answer # 3

    I think it's easy to apply by creating a correspondence table and applying conversion.

    correspondence_table =% w [〇 1 2 3 4 5 6 7 8 9] .zip ([* '0' .. '9']) .to_h
    '123 issue'.gsub (/ [01 2343 6789] (?! Issue) /) {| s | correspondence_table [s]}
    # =>"12 No. 3"

    I don't know if the regular expression is correct, but for the time being, it can be converted except for Chinese numerals that have a "go" immediately after them.