2013-08-11 2 views
-1

다음 문장이있는 파일이 있습니다.정규식 패턴과 파이썬 함수가 필요합니다.

start < some 50 words > End   //need to work only on these types 
start < some 50 words > 
start < some 50 words > End 
start < some 50 words > 
< some 50 words > End 

...이 패턴은 10000 번 반복됩니다. 나는 시작 부분에있는 '시작'난 그냥 시작과 끝을 수정하는 사이에 같은 단어를 계속해야

start2 <same 50 words > End2. 

에 결국 '끝'이 선을 교체합니다.

답변

1
import re 

data = """start < some 50 words > End 
start < some 50 words > 
start < some 50 words > End 
start < some 50 words > 
< some 50 words > End 
""" 

print re.sub('start(.*)End', 'start2\g<1>End.', data) 

인쇄 :이 문제에 대한에 갈 필요가보다

start2 < some 50 words > End. 
start < some 50 words > 
start2 < some 50 words > End. 
start < some 50 words > 
< some 50 words > End 
+0

This \ g <1>은 나에게 새로운 이야기입니다.이게 무엇인지 자세히 설명해 주시겠습니까? 답장을 보내 주셔서 감사합니다. –

+0

저장된 그룹을 참조하는 방법 일 뿐이며,이 경우에는'(. *) '입니다. – alecxe

1

정규 표현식이 더 많은 작업입니다 - 그것은 모든 평범한 구식 문자열 방법보다 간단하게 수행 할 수 있습니다

def ReplaceStartEnd(s): 
... if s.startswith("start") and s.endswith("End"): 
...  return "start2" + s[5:-3] + "End2" 
... else: 
...  return s