Python을 사용하여 파일의 함수 블록 교체

Sep 04 2020

각 파일에서 변경해야하는 여러 파일에 Ruby 함수 코드 블록이 있습니다.

대체하려는 기능은 다음과 같습니다.

    def func1 options
        ...
        some code here
        ...
        def inner_func1 inner_options
            ...
            some code here
            ...
        end
        ...
        some more code here
        ...
    end

각 파일에는 다른 기능이 있지만 이름은 다릅니다. 일부 파일에서는 이전에 여러 개의 탭이나 공백이있을 수 있습니다.

func1각 파일의를 다른 파일 (매개 변수에 전달 된 변수 일 수 있음)에서 읽은 내용 으로 바꾸고 싶습니다 .

지금까지 이러한 파일 중 하나를 변경하기 위해 다음 파이썬 함수를 작성했습니다.

import re

a = open('main.rb').read() # file where I have the func1
b = open('modified.rb').read() # file where I have only the modified func1 

c = re.sub('(^[ \t]*)def func1:$.?\1end$',b,a, flags=re.DOTALL)

print(c)

with open('main.rb', 'w') as filetowrite:
    filetowrite.write(c)
        

그러나 내 c문자열에는 아무것도 변경되지 않았습니다.

내 정규식에 문제가 있는지 확실하지 않습니다.

답변

1 Liju Sep 04 2020 at 18:04

정규식 아래에서 시도하십시오

(?:^|\n)([\t ]*?)def func1 options[\s\S]*?\n\1end

암호

import re

input="""
def func1 options
    some code here
    def inner_func1 inner_options
        some code here
    end
    some more code here
end
"""

replacement="""
def new_func1 options
    new code here
end
"""

print(re.sub(r"(?:^|\n)([\t ]*?)def func1 options[\s\S]*?\n\1end",replacement,input),end='')

산출

def new_func1 options
    new code here
end

Regex 데모 | Python 데모