2013-05-31 36 views
10

İşte benim kod:Python regex arama

#!/usr/bin/python 
import io 
import re 
f = open('/etc/ssh/sshd_config','r') 
strings = re.search(r'.*IgnoreR.*', f.read()) 
print(strings) 
veri döndürür

ama belli Normal ifade eşlemeyi gerekir: Ben kodunu değiştirmek durumunda

^\s*[^#]*IgnoreRhosts\s+yes 

: örneğin basitçe için:

strings = re.search(r'^IgnoreR.*', f.read()) 

hatta

strings = re.search(r'^.*IgnoreR.*', f.read()) 

Geri bir şey alamıyorum. Bu modda olmadan her zaman \n tarafından ^ takabilmek

#!/usr/bin/python 
import io 
import re 
f = open('/etc/ssh/sshd_config','r') 

strings = re.search(r"^\s*[^#]*IgnoreRhosts\s+yes", f.read(), flags=re.MULTILINE) 
print(strings.group(0)) 

Not: Ben

+0

Neden "re.search (r"^\ s * [^ #] * IgnoreRhosts \ s + yes ", f.read())' yi kullanmıyorsunuz? –

+0

Python'un regex sözdizimi, perl'in – SethMMorton

+0

ile aynıdır.^Ign çalışmıyorsa, r '^ \ s * [^ #] * IgnoreRhosts \ s + yes' işlevini kullanamazsınız. En düşük ortak paydayı arıyordum. –

cevap

16

Bir satırın başlangıcını maç sonra satırlı modunu kullanabilirsiniz^edebilirsiniz perl'de gibi regex gerçek kullanmak gerekiyor

Not da bu dosya böylece domates şekilde kalibre edildiğini:

^IgnoreRhosts\s+yes 

par kontrol için yeterince iyi


DÜZENLEME ameter: daha iyi bir yol

with open('/etc/ssh/sshd_config') as f: 
    for line in f: 
     if line.startswith('IgnoreRhosts yes'): 
      print(line) 

Bir kez daha gelen boşluklar için hiçbir neden yoktur. Ancak emin olmak istiyorsanız, her zaman lstrip()'u kullanabilirsiniz.

+3

Ne demek domates gibi kalibre edilmiş? –

+0

@GlitchCowboy: her zaman aynı –

+0

Tamam, multiline sihirdi. 'stringler = re.findall (r"^\ s * [^ #] * IgnoreRhosts \ s + evet ", f.read(), flags = re.MULTILINE) dizgilerdeki öğe için: print (item)' –