텍스트의 멀티 라인 블록과 일치하지만 교체하지 않는 파이썬 정규식
문제
좋아,이 코드가 있습니다.
def findNReplaceRegExp(file_name, regexp, replaceString, verbose=True, confirmationNeeded=True):
'''Replaces the oldString with the replaceString in the file given,\
returns the number of replaces
'''
# initialize local variables
cregexp = re.compile(regexp, re.MULTILINE | re.DOTALL)
somethingReplaced = True
ocurrences = 0
isAborted = False
# open file for read
file_in = open(file_name, 'r')
file_in_string = file_in.read()
file_in.close()
while somethingReplaced:
somethingReplaced = False
# if the regexp is found
if cregexp.search(file_in_string):
# make the substitution
replaced_text = re.sub(regexp, replaceString, file_in_string)
if verbose == True:
# calculate the segment of text in which the resolution will be done
# print the old string and the new string
print '- ' + file_in_string
print '+ ' + replaced_text
if confirmationNeeded:
# ask user if this should be done
question = raw_input('Accept changes? [Yes (Y), No (n), Abort (a)] ')
question = string.lower(question)
if question == 'a':
isAborted = True
print "Aborted"
break
elif question == 'n':
pass
else:
file_in_string = replaced_text
somethingReplaced = True
ocurrences = ocurrences + 1
else:
file_in_string = replaced_text
somethingReplaced = True
ocurrences = ocurrences + 1
# if some text was replaced, overwrite the original file
if ocurrences > 0 and not isAborted:
# open the file for overwritting
file_out = open(file_name, 'w')
file_out.write(file_in_string)
file_out.close()
if verbose: print "File " + file_name + " written"
그리고이 파일
CMC_SRS T10-24400: DKU Data Supply: SN Time Break-In Area
CMC_SRS T10-24401: DKU Data Supply: SN Transponder Enable Area
CMC_SRS T10-24402: DKU Data Supply: SN Adjust Master Slave Area
CMC_SRS T10-24403: DKU Data Supply: SN ATEC Area
CMC_SRS T10-24404: DKU Data Supply: SN PTEC Area
CMC_SRS T10-25449: DKU Data Supply: SN Self Init Area
CMC_SRS T10-24545: DKU Data Supply: SN Time Area
CMC_SRS T10-4017: RFI display update
CMC_SRS T10-6711: Radio Interface to PLS Equipment
CMC_SRS T10-21077: Safety Requirements: Limit FM Power
이 파일 과이 매개 변수로 절차를 호출 할 때 : regexp = 24403.*24404 REPLEC = TESTSTRING
나는 우연의 일치를 얻습니다 (일치하고 무엇을 해야하는지 의문) 아무것도 대체 할 시간이있을 때 ... 무슨 일이 일어나는지 ... 무슨 일인가 ??
해결책
당신은 함께 찾고 있습니다 cregexp
, 멀티 틸린 옵션 세트가 있지만 대체 regexp
, 그렇지 않을 수도 있습니다.
제휴하지 않습니다 StackOverflow