2010-02-24 75 views
0

我正在嘗試爲LyX文件編寫一個字計數器。Ruby中的文本處理

生活幾乎是非常簡單的,因爲大多數需要忽略的行都以\開頭(我準備假設沒有文本行以反斜槓開始) - 但是有一些行看起來像真正的文本都沒有,但它們是由\begin_inset\end_inset封閉:

I'm genuine text. 

\begin_inset something 
I'm not real text 
Perhaps there will be more than one line! Or none at all! Who knows. 
\end_inset 

/begin_layout 
I also need to be counted, and thus not removed 
/end_layout 

是否有紅寶石的快捷方式剝離兩個標記之間的文本(最小的量)?我想象正規表達式是前進的方向,但我無法弄清楚他們必須做什麼。

在此先感謝

回答

3

是否有紅寶石的快捷方式剝奪兩個標記之間的文本(最小的量)?

str = "lala BEGIN_MARKER \nlu\nlu\n END_MARKER foo BEGIN_MARKER bar END_MARKER baz" 
str.gsub(/BEGIN_MARKER.*?END_MARKER/m, "") 
#=> "lala foo baz" 
+0

D'oh! *當然是砸頭了 - 謝謝! – 2010-02-24 18:25:47

1

GSUB可能是更長的文件昂貴

左右(如果你在整個文件作爲字符串讀取),如果你有塊也無妨,你可能想使用一個狀態解析器

in_block = false 
File.open(fname).each_line do |line| 
if in_block 
    in_block = false if line =~ /END_MARKER/ 
    next 
    else 
    in_block = true if line =~ /BEGIN_MARKER/ 
    next 
    end 
    count_words(line) 
end 
0

你應該看看str.scan()。假設你的文本在變量s中,像這樣的東西應該工作:

s_strip_inset = s.sub!(/\\begin_inset.*?\\end_inset/, "") 
word_count = s_strip_inset.scan(/(\w|-)+/).size