2016-11-14 115 views
0

的開頭我想要做字符串替換在Ruby中,但只有當某些條件滿足。負前瞻 - 在字符串

與「快板」替換「allegro4」的所有出現時,該行不與#include聲明開始。我嘗試過,但我沒有取得任何成功。替代根本沒有完成。

"#include <allegro4/allegro4.h>".gsub(/(?!#include) allegro4/, 'allegro') 

望着負向前看符號的其他例子,試圖irb不同的事情使我相信,有一個專門的字符串的開頭負向前看符號事情很奇怪。

+0

什麼是你的問題? – sawa

回答

1
R =/
    \A    # match beginning of string 
    (?!\#include) # do not match '#include' at start of string (negative lookahead) 
    .*?    # match any number of any character 
    <    # match '<' 
    \K    # forget everything matched so far 
    allegro   # match string 
    (\d+)   # match one or more digits in capture group 1 
    \/allegro  # match string 
    \1    # match the contents of capture group 1 
    /x    # Free-spacing regex definition mode 

def replace_unless(str) 
    str.gsub(R, 'allegro/allegro') 
end 

replace_unless "cat #include <allegro4/allegro4.h>" 
    #=> "cat #include <allegro/allegro.h>" 
replace_unless "cat #include <allegro4/allegro3.h>" 
    #=> "cat #include <allegro4/allegro3.h>" 
replace_unless "#include <allegro4/allegro4.h>" 
    #=> "#include <allegro4/allegro4.h>" 

我已經假定特定字符串「快板」是相匹配的,任何非負整數可以遵循的「快板」,但一個不能有「兩個實例以下不同數量的兩個實例快板」。如果該數字必須是4,請將正則表達式中的(\d+)\1替換爲4。如果'allegro'僅僅是任何小寫字母串的替身,那麼正則表達式可以被改變如下。

R =/
    \A    # match beginning of string 
    (?!\#include) # do not match '#include' at start of string (negative lookahead) 
    .*    # match any number of any character 
    <    # match character 
    \K    # forget everything matched so far 
    ([[:lower:]]+) # match one or more lower-case letters in capture group 1 
    (\d+)   # match one or more digits in capture group 2 
    \/    # match character 
    \1    # match the contents of capture group 1 
    \2    # match the contents of capture group 2 
    /x    # Free-spacing regex definition mode 

def replace_unless(str) 
    str.gsub(R, '\1/\1') 
end 

replace_unless "cat #include <cats9/cats9.h>" 
    #=> "cat #include <cats/cats.h>" 
replace_unless "dog #include <dogs4/dogs3.h>" 
    #=> "dog #include <dogs4/dogs3.h>" 
replace_unless "#include <pigs4/pigs4.h>" 
    #=> "#include <pigs4/pigs4.h>"