2008-12-15 72 views
2

使用Ruby我想下面的文字用正則表達式紅寶石正則表達式匹配,除非逃脫

~foo\~\=bar =cheese~monkey 

裏劈〜或=表示比賽開始,除非它與\

逃脫因此,它應該符合

~foo\~\=bar 

然後

=cheese 

然後

~monkey 

我想下面的工作,但事實並非如此。

([~=]([^~=]|\\=|\\~)+)(.*) 

什麼是更好的正則表達式使用?

編輯更具體地,上述正則表達式的所有出現匹配=和〜

編輯工作溶液。這是我想出來解決這個問題。我發現Ruby 1.8展望未來,但不具有向後看功能。環顧了一下後,所以,我在comp.lang.ruby跨this post來了,和下面的完成它:

# Iterates through the answer clauses 
def split_apart clauses 
    reg = Regexp.new('.*?(?:[~=])(?!\\\\)', Regexp::MULTILINE) 

    # need to use reverse since Ruby 1.8 has look ahead, but not look behind 
    matches = clauses.reverse.scan(reg).reverse.map {|clause| clause.strip.reverse} 

    matches.each do |match| 
    yield match 
    end 
end 
+0

你可以發佈你的工作解決方案嗎?我想看看它。乾杯! ;-) – Tomalak 2008-12-17 07:25:00

回答

4

什麼是「刪除頭」的意思是在這方面?

如果你想刪除某個字符之前的一切,這是不行的:

.*?(?<!\\)=  // anything up to the first "=" that is not preceded by "\" 
.*?(?<!\\)~  // same, but for the squiggly "~" 
.*?(?<!\\)(?=~) // same, but excluding the separator itself (if you need that) 

通過「」,重複,完成替換。

如果字符串恰好有三個要素("1=2~3"),你想一次滿足所有的人,你可以使用:

^(.*?(?<!\\)(?:=))(.*?(?<!\\)(?:~))(.*)$ 

matches: \~foo\~\=bar =cheese~monkey 
     |  1  | 2 | 3 | 

或者,您可以使用此正則表達式分割字符串:

(?<!\\)[=~] 

returns: ['\~foo\~\=bar ', 'cheese', 'monkey'] for "\~foo\~\=bar =cheese~monkey" 
returns: ['', 'foo\~\=bar ', 'cheese', 'monkey'] for "~foo\~\=bar =cheese~monkey" 
+0

原來,我使用的Ruby版本中的正則表達式不支持後顧之外,但我可以使用它來使它工作。 – 2008-12-17 00:35:35