Mega Code Archive

 
Categories / Python Tutorial / Regular Expressions
 

Grouping and greedy operations

import re formatString1 = "%-22s: %s"   # string to format output  testString1 = "phone: 123-4567, e-mail: a@server.com" expression1 = r"(\w+ \w+), phone: (\d{3}-\d{4}), e-mail: (\w+@\w+\.\w{3})" formatString2 = "%-38s: %s"   # string to format output pathString = "/books/2001/python"  # file path string expression2 = "(/.+)/"  # greedy operator expression print formatString1 % ( "Greedy error",re.match( expression2, pathString ).group( 1 ) ) expression3 = "(/.+?)/"  # non-greedy operator expression print formatString1 % ( "No error, base only",re.match( expression3, pathString ).group( 1 ) )