作者fbukevin (Veck)
看板Ruby
標題[問題] =~
時間Mon Jul 19 15:43:18 2010
大家好
我碰到的問題是下列程式碼執行的結果:
#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)
1F:→ shelary:不要用 big5 看看丫..用 utf8 07/19 15:47
2F:→ fbukevin:剛試過的,還是會出狀況>< 07/19 16:04
3F:→ godfat:你的檔案是啥編碼..? 07/19 16:05
4F:→ fbukevin:我試過ANSI、Unicode和UTF8存檔,但都有相同問題耶! 07/19 18:53
5F:推 zero00072:yyy.txt 裡面有中文嗎?有中文的話,正規式好像不支援。 07/19 21:16
6F:推 godfat:ruby 1.9 的 regexp 支援所有支援的編碼,你一定哪裡設錯.. 07/20 01:14
7F:推 zero00072:嗯嗯,板主說的對,正規式已經可以對所有的碼支援了。 07/20 09:15
8F:推 zero00072:我試過也沒問題,ruby 1.9.2、UTF-8、GNU/Linux。 07/20 09:28
9F:→ zero00072:open(ARGV[1]).each do |text| 07/20 09:32
10F:→ zero00072: puts text if text =~ Regexp.new(ARGV[0]) 07/20 09:33
11F:→ zero00072:end 07/20 09:33
12F:推 hellolucky:pattern和text寫反了? text =~ pattern ?? 08/19 23:52
13F:→ hellolucky:不是說樓上 是說原文 08/19 23:53