2016-11-14 21 views
0

私はRubyで文字列の置換を行いたいですが、特定の条件がでない場合にのみ、が満たされます。負のルックアヘッド - 文字列の先頭で

行が#includeステートメントで始まらない場合、 'allegro4'のすべての出現箇所を 'allegro'に置き換えます。私はこれを試みたが、私は成功していない。置換は単に行われません。

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

負の先読みの他の例を見てみるとirbに異なるものをしようとは、具体的には、文字列の先頭に負の先読みで起こって奇妙な何かがあると信じて私をリードしています。私は、特定の文字列は「アレグロ」はマッチされるべきであり、任意の非負整数「アレグロ」の両方のインスタンスに従うことができるが、一方が「アレグロの2つのインスタンス以下の異なる番号を持つことができないと仮定した

+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>" 
関連する問題