Regex in python. How to simplify my example? -
i'm new @ python programming. right i'm struggling simplifying existing code. here exercise: develop pattern match telephone number in format (xxx) xxx-xx-xx
, xxx-xxx-xx-xx
. i've come far:
patt = "\(?\d{3}\)?\s?-?\d{3}-\d{2}-\d{2}"
it works perfectly. problem obvious: if have optional pattern, say, "(specific-patter-ffddff445%$#%)--ds"
before kind of fixed pattern, have put "?" symbol before every symbol in optional pattern. how can combine symbols , put 1 "?" mark?
so have matches kinds of incorrect formats. example:
012)345-67-89
(012 345-67-89
what want option, regexes provide you: https://docs.python.org/3.4/library/re.html#regular-expression-syntax
something preferable:
patt = '(?:\(\d{3}\) |\d{3}-)\d{3}-\d{2}-\d{2}'
this match either "(xxx) " or "xxx-" prefix "xxx-xx-xx". , not match either of error strings listed above.
?
should used in event operates on optional.
Comments
Post a Comment