Type of regular expression
Peter Otten
__peter__ at web.de
Fri Jul 2 04:30:36 EDT 2004
More information about the Python-list mailing list
Fri Jul 2 04:30:36 EDT 2004
- Previous message (by thread): Type of regular expression
- Next message (by thread): Type of regular expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Joakim Hove wrote: > > Peter Otten <__peter__ at web.de> writes: > >> Joakim Hove wrote: >> >>> I wondered how I could test wether an argument was of type compiled >>> regexp: >> >> Both strings and compiled regular expressions can be compiled: > > [...] > >> Therefore I would not test beforehand, just rely on re.compile() to know >> what it can deal with: >> >>>>> def do_something(s): >> ... try: >> ... s = re.compile(s) >> ... except TypeError: >> ... sys.exit("Something went wrong") >> ... # more stuff >> ... > > Thanks for answering, however I am afraid i posed the question > somewhat ambigously: The point is that i want the function to do > different things depending on the type of input: The easiest way to get the type of regular expressions: >>> import re >>> r = re.compile("") >>> RegexType = type(r) >>> del r The types has examples where it's done in exactly the same way. Now do the test: >>> isinstance(re.compile("abc"), RegexType) True >>> isinstance("abc", RegexType) False An alternative would be to test for the part of the interface you are interested in (the match() method in the following example): >>> r = re.compile("abc") >>> if hasattr(r, "match"): ... print "it's a regexp" ... else: ... print "it's a string" ... it's a regexp Peter
- Previous message (by thread): Type of regular expression
- Next message (by thread): Type of regular expression
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list