/me hat geschrieben:Ich glaube du siehst da ein Problem wo keins ist.
Wollte das jetzt fast auch schon glauben,
wobei ich tatsächlich nur auf "die falsche Seite" geschaut hab'. Ich hatte einfach mal spaßeshalber folgendes gemacht...
Code: Alles auswählen
def test():
s = raw_input('String : ')
while True:
r = raw_input('Regex : ')
if not r:
s = raw_input('String : ')
r = raw_input('Regex : ')
print 'findall: {}'.format(re.findall(r, s))
... und mich gewundert, weshalb das dabei herauskommt:
Code: Alles auswählen
String : string with \n newline and \backslash.
Regex : (\w+)
findall: ['string', 'with', 'n', 'newline', 'and', 'backslash']
Jetzt ging ich davon aus, dass "irgendwas" mit der regex nicht stimmen kann. Das "Problem" ist allerdings folgendes:
Code: Alles auswählen
>>> 'string with \n newline and \backslash.'
'string with \n newline and \x08ackslash.'
>>> raw_input('> ')
> string with \n newline and \backslash.
'string with \\n newline and \\backslash.'
>>> raw_input('> ').decode('string_escape')
> string with \n newline and \backslash.
'string with \n newline and \x08ackslash.'
Wenn ich also den via ``raw_input()`` eingelesenen string erstmal dekodiere, erhalte ich auch, was ich erwartet habe:
Code: Alles auswählen
def test():
s = raw_input('String : ').decode('string_escape')
while True:
r = raw_input('Regex : ')
if not r:
s = raw_input('String : ').decode('string_escape')
r = raw_input('Regex : ')
print 'findall: {}'.format(re.findall(r, s))
Code: Alles auswählen
String : string with \n newline and \backslash.
Regex : (\w+)
findall: ['string', 'with', 'newline', 'and', 'ackslash']
Regex :
String : string with \n newline and \\backslash.
Regex : (\w+)
findall: ['string', 'with', 'newline', 'and', 'backslash']
Was ich jetzt allerdings nicht verstehe: Weshalb die Magie in ``raw_input()``? Wohin wird ``s`` eigentlich decodiert?
mutetella