pattern match !

Jay Loden python at jayloden.com
Wed Jul 11 17:12:51 EDT 2007


Helmut Jarausch wrote:
> hari.siri74 at gmail.com wrote:
>> Extract the application name with version from an RPM string like
>> hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0
>> from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3-
>> Linux.RPM.
>>
> 
> Have a try with
> 
> import re
> P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM')
> S="hpsmh-1.1.1.2-0-RHEL3-Linux.RPM"
> PO= P.match(S)
> if  PO :
>    print PO.group(1)


A slightly more generic match in case your package names turn out to be less consistent than given in the test cases:

#!/usr/bin/python

import re
pattern = re.compile(r'(\w+?-(\d+[\.-])+\d+?)-\D+.*RPM')
pkgnames = ["hpsmh-1.1.1.2-0-RHEL3-Linux.RPM", "hpsmh-1.1.1.2-RHEL3-Linux.RPM"]
for pkg in pkgnames:
  matchObj = pattern.search(pkg)
  if matchObj:
    print matchObj.group(1)

Still assumes it will end in RPM (all caps), but if you add the flag "re.I" to the re.compile() call, it will match case-insensitive. 

Hope that helps, 

-Jay



More information about the Python-list mailing list