2013-05-23 3 views
209

나는 매개 변수가 임의의 순서가 있습니다 만, 한 줄에 하나의 매개 변수가 형태파이썬하려면 string.replace 정규 표현식

parameter-name parameter-value 

의 매개 변수 파일이 있습니다. 한 매개 변수의 매개 변수 값을 새 값으로 바꾸려고합니다.

파이썬의 string.replace (pattern, subst)을 사용하는 줄을 바꾸려면 이전에 게시 한 줄 바꾸기 기능 (Search and replace a line in a file in Python)을 사용하고 있습니다. 예를 들어 vim에서 사용하는 정규식은 string.replace에서 작동하지 않습니다. interfaceOpDataFile 난 (대소 문자 구분을위한/I)를 교환하고있어, 새로운 매개 변수 값은 fileIn 변수의 내용 인 파라미터 이름이

line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn)) 

을 : 여기에 사용하고 일반 식이다. 파이썬이이 정규식을 인식하도록하는 방법이 있습니까? 그렇지 않으면이 작업을 수행하는 다른 방법이 있습니까? 미리 감사드립니다.

답변

310

str.replace()v2 | v3은 정규식을 인식하지 못합니다.

re.sub() v2를 사용하여 정규 표현식을 사용하여 대체를 수행하려면 | v3. 예를 들어

: 루프에서

import re 

line = re.sub(
      r"(?i)^.*interfaceOpDataFile.*$", 
      "interfaceOpDataFile %s" % fileIn, 
      line 
     ) 

, 먼저 정규 표현식을 컴파일 좋을 것이다 : 당신은 re.sub 기능을 찾고 있습니다

import re 

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE) 
for line in some_file: 
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line) 
    # do something with the updated line 
+19

으로 – pokero

+3

이것을 작동 시키려면're.sub'의 마지막 인자로'flags = re.MULTILINE'을 넘겨 줘야합니다. [Read here for the docs here] (https : // docs .python.org/2/library/re.html # re.MULTILINE) – tobek

+2

정규식 컴파일이 캐시됩니다 ([docs] (https://docs.python.org/3.6/library/re.html#re.compile)). 컴파일이 필요하지 않습니다. 그러나 보여 주듯이, 하나가 컴파일되면 루프 외부에서 컴파일하십시오. 'interfaceOpDataFile SomeDummyFile.txt' 내가로 교체하는 것이 좋습니다 : 'interfaceOpDataFile SomeUsefulFile 원본 파일 같은 것을 가지고 있기 때문에 – alttag

188

.

import re 
s = "Example String" 
replaced = re.sub('[ES]', 'a', s) 
print replaced 

은 당신이 찾고있는 것을 axample atring

8

re.sub은 확실히 인쇄됩니다. 아시다시피 앵커와 와일드 카드가 필요하지 않습니다. "interfaceOpDataFile"처럼 보이는 첫 번째 문자열을 일치하고 교체 -

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line) 

같은 일을 할 것입니다. 감사 - 루프 외부에서 컴파일하여 요약

import sys 
import re 

f = sys.argv[1] 
find = sys.argv[2] 
replace = sys.argv[3] 
with open (f, "r") as myfile: 
    s=myfile.read() 
ret = re.sub(find,replace, s) # <<< This is where the magic happens 
print ret 
+0

나는 줄 전체를 교체해야합니다.txt' 앵커를 포함하지 않으면'SomeDummyFile.txt'를 없애고 싶다는 것을 어떻게 대체할까요? –

+0

아, 나는 당신이 대체품으로 무엇을하고 있었는지 정확히 이해하지 못했습니다. 각 쌍이 자체 회선에 있으면 앵커가 명확하지 않아도됩니다. 're (r "(? i) (interfaceOpDataFile). *", r '\ 1 UsefulFile', line)'이것은 전체 라인을 취하고, arguement 이름을 캡쳐 한 다음, 그것을 대신하여 당신을 대신하여 추가합니다. – Nelz11

7

훌륭한 조언이 좋은 뉘앙스이다.