tingel
Goto Top

PHP zu Python - Hilfe

Hallo zusammen,

Ich möchte von PHP zu Python wechseln und habe dort ein kleines Problem.
In PHP habe ich folgenden funktionierenden Code:
<?php

$text = 'Maße : 1 Beleg-Nr. : 2';  
$match1 = "";  
$match2 = "";  

if (preg_match("/Ma\S+?e(?:\s[\s:._]*)(.*?)\ Beleg\S+[.:\-\t\ ]+(.*)/i", $text, $treffer)) {  
        $match1 = trim($treffer[1]);
		$match2 = trim($treffer[2]);
    }

echo "Treffer 1: " . $match1 . "\n";  
echo "Treffer 2: " . $match2 . "\n";  

In Python sieht es momentan so aus:
import re
p = re.compile( "/Ma\\S+?e(?:\\s[\\s:._]*)(.*?)\\ Beleg\\S+[.:\\-\\t\\ ]+(.*)/i" );  
m = p.search( "Masse : 1 Beleg-Nr. : 2");  
if m:
    print ("Match found");  
else:
    print ("No match");  

In PHP werden die Suchbegriffe gefunden und gibt auch die gewünschten Zahlen aus.
In Python findet er nichts (Ausgabe: "No match" (Der Einfachkeitshalber)).

Woran liegt das? Kann mir da jemand helfen?

Content-Key: 307053

Url: https://administrator.de/contentid/307053

Printed on: April 26, 2024 at 18:04 o'clock

Member: Dirmhirn
Dirmhirn Jun 14, 2016 at 08:21:58 (UTC)
Goto Top
Hi,

hast du dir die Werte schon zwischendurch angeschaut?
re, p, m

ev. kommt es hier aus anderen Gründen zu m == false.

sg Dirm
Member: tingel
tingel Jun 14, 2016 updated at 13:05:54 (UTC)
Goto Top
Hallo,
ich weiß nicht, ob das so stimmt, aber mit
re.compile( 'Ma\\S+?e(?:\\s[\\s:._]*)(.*?)\\ Beleg\\S+[.:\\-\\t\\ ]+(.*)' );
findet er was.

Weiß jemand, wie ich
$match1 = trim($treffer[1]);
$match2 = trim($treffer[2]);

umsetzen kann?
Member: colinardo
Solution colinardo Jun 17, 2016 updated at 19:26:37 (UTC)
Goto Top
Hallo tingel:
das sind einfach Regular Expression Submatches, die im Regex geklammerten Subgroups kannst du z.B. so ansprechen:
#!/usr/bin/python
import re
match = re.match('(?i)Ma\S+?e(?:\s[\s:._]*)(.*?) Beleg\S+[.:\-\t\ ]+(.*)','Masse : 1 Beleg-Nr. : 2')  
if match:
	submatch1 = match.group(1)
	submatch2 = match.group(2)
	print submatch1
	print submatch2
else:
	print "Kein Treffer"  
https://docs.python.org/2.7/library/re.html#match-objects

Grüße Uwe
Member: tingel
tingel Jun 17, 2016 at 14:53:38 (UTC)
Goto Top
Vielen Dank!!