[問題] =~

看板Ruby作者 (Veck)時間14年前 (2010/07/19 15:43), 編輯推噓5(508)
留言13則, 5人參與, 最新討論串1/1
大家好 我碰到的問題是下列程式碼執行的結果: #encoding : big5 pattern = Regexp.new(ARGV[0]) filename = ARGV[1] file = open(filename) while text =file.gets do if pattern =~ text print text end end file.close 這是我照書上打的程式 但是當我執行時輸入: ruby 檔名.rb xxx yyy.txt 之後就會顯示出錯誤訊息: grep.rb:10:in `=~': invalid byte sequence in Big5 (ArgumentError) from grep.rb:10:in `<main>' 為什麼會這樣?我照書上的寫,同一個目錄下也真的有yyy.txt 找不到錯誤QQ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.170.224.200 ※ 編輯: fbukevin 來自: 118.170.224.200 (07/19 15:43)

07/19 15:47, , 1F
不要用 big5 看看丫..用 utf8
07/19 15:47, 1F

07/19 16:04, , 2F
剛試過的,還是會出狀況><
07/19 16:04, 2F

07/19 16:05, , 3F
你的檔案是啥編碼..?
07/19 16:05, 3F

07/19 18:53, , 4F
我試過ANSI、Unicode和UTF8存檔,但都有相同問題耶!
07/19 18:53, 4F

07/19 21:16, , 5F
yyy.txt 裡面有中文嗎?有中文的話,正規式好像不支援。
07/19 21:16, 5F

07/20 01:14, , 6F
ruby 1.9 的 regexp 支援所有支援的編碼,你一定哪裡設錯..
07/20 01:14, 6F

07/20 09:15, , 7F
嗯嗯,板主說的對,正規式已經可以對所有的碼支援了。
07/20 09:15, 7F

07/20 09:28, , 8F
我試過也沒問題,ruby 1.9.2、UTF-8、GNU/Linux。
07/20 09:28, 8F

07/20 09:32, , 9F
open(ARGV[1]).each do |text|
07/20 09:32, 9F

07/20 09:33, , 10F
puts text if text =~ Regexp.new(ARGV[0])
07/20 09:33, 10F

07/20 09:33, , 11F
end
07/20 09:33, 11F

08/19 23:52, , 12F
pattern和text寫反了? text =~ pattern ??
08/19 23:52, 12F

08/19 23:53, , 13F
不是說樓上 是說原文
08/19 23:53, 13F
文章代碼(AID): #1CH08PE2 (Ruby)