2012-08-14 14 views
6

Quando ho cambiato due parole in una stringa con altre due parole usando re.sub ho ottenuto l'output. Ma quando ho provato che con uscita numeri non viene correttamenteSostituzioni multiple di numeri nella stringa usando regex python

>>> import re 
>>> a='this is the string i want to change' 
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','wanted'),a) 
'this was the string i wanted to change' 
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','12345'),a) 
'this was\x8a345 to change' 
>>> 

non so il motivo per cui questo accade potrebbe u piacere tel me come usare questo Grazie in anticipo

risposta

7

Quello che succede è che si' rientrando nella sostituzione r'\1was\212345\3', e Python non può determinare se si desidera il numero di riferimento 2, 21, 211, .... Seleziona solo il più grande, 212345, che ovviamente non è un indice di gruppo nella tua espressione. Pertanto, Python decide che intendevi il letterale letterale b'\212', che è uno strano modo di scrivere lo b'\x8a'.

Per risolvere l'ambiguità, utilizzare la sintassi lungo backreference, \g<GROUP_NUMBER_HERE>:

>>> re.sub('(.*)is(.*)want(.*)','\\g<1>%s\\g<2>%s\\g<3>' %('was','12345'),a) 
'this was the string i 12345 to change' 
+0

Grazie mille. Sembra buona. – Myjab

Problemi correlati