473,396 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Type of regular expression


Hello,

I wondered how I could test wether an argument was of type compiled
regexp:

from types import *

def do_something(arg):
if type(arg) is StringType:
print "%s is a string" % arg
elsif type(arg) is RegexpType: # <- This constant does not
# exist, it is only
# something I invented.
print "%s is a regexp" % arg
else
sys.exit("Argument must be *either* string or regular expression")

which is then called as:

do_something("a string")
do_something(re.compile("^F")

Regards

Joakim

--
/--------------------------------------------------------------------\
/ Joakim Hove / ho**@bccs.no / (55 5) 84076 | \
| Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 |
| CMU | 5231 Paradis |
\ Thormøhlensgt.55, 5020 Bergen. | 55 91 28 18 /
\--------------------------------------------------------------------/
Jul 18 '05 #1
6 1652
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:
import re
r = re.compile("abc")
s = re.compile(r)
r is s True

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
.... do_something("abc")
do_something(r)
do_something(1)

Something went wrong

Peter

Jul 18 '05 #2

Peter Otten <__*******@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:

def do_something(arg):
if type(arg) is RegexpType:
# Handle regular expression argument
elsif type(arg) is StringType:
# Handle string argument - which is something
# completely different.
else:
sys.exit("Wrong argument type")
Thanks - Joakim

--
/--------------------------------------------------------------------\
/ Joakim Hove / ho**@bccs.no / (55 5) 84076 | \
| Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 |
| CMU | 5231 Paradis |
\ Thormøhlensgt.55, 5020 Bergen. | 55 91 28 18 /
\--------------------------------------------------------------------/
Jul 18 '05 #3
Joakim Hove wrote:

Peter Otten <__*******@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
Jul 18 '05 #4
Peter Otten wrote:
The types has examples where it's done in exactly the same way.

The types module has examples where it's done in exactly the same way.
Jul 18 '05 #5

Peter Otten <__*******@web.de> writes:

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


That was elegant - thanks a lot.
Joakim
--
/--------------------------------------------------------------------\
/ Joakim Hove / ho**@bccs.no / (55 5) 84076 | \
| Unifob AS, Avdeling for Beregningsvitenskap (BCCS) | Stabburveien 18 |
| CMU | 5231 Paradis |
\ Thormøhlensgt.55, 5020 Bergen. | 55 91 28 18 /
\--------------------------------------------------------------------/
Jul 18 '05 #6
In article <4y************@skjellgran.ii.uib.no>,
Joakim Hove <ho**@bccs.no> wrote:

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:

def do_something(arg):
if type(arg) is RegexpType:
# Handle regular expression argument
elsif type(arg) is StringType:
# Handle string argument - which is something
# completely different.
else:
sys.exit("Wrong argument type")


That's a Bad Idea. What if someone gives you a Unicode string?
Generally speaking, type-based dispatch will run into problems sooner or
later. The better approach: you have to know at some point what kind of
data is being passed around -- when you create a target (usually a name)
for it. If you really need to know the type later on, create a
container that includes the necessary type information.
--
Aahz (aa**@pythoncraft.com) <*> http://www.pythoncraft.com/

"Typing is cheap. Thinking is expensive." --Roy Smith, c.l.py
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Ron Adam | last post by:
Is it possible to match a string to regular expression pattern instead of the other way around? For example, instead of finding a match within a string, I want to find out, (pass or fail), if...
2
by: Bryce Budd | last post by:
Hi all, I am trying to use a regular expression validator to check for the existence of PO Box in an address textbox. The business rule is "No addresses with PO Boxes are allowed." What I...
4
by: Buddy | last post by:
Can someone please show me how to create a regular expression to do the following My text is set to MyColumn{1, 100} Test I want a regular expression that sets the text to the following...
11
by: Dimitris Georgakopuolos | last post by:
Hello, I have a text file that I load up to a string. The text includes certain expression like {firstName} or {userName} that I want to match and then replace with a new expression. However,...
18
by: Q. John Chen | last post by:
I have Vidation Controls First One: Simple exluce certain special characters: say no a or b or c in the string: * Second One: I required date be entered in "MM/DD/YYYY" format: //+4 How...
7
by: Billa | last post by:
Hi, I am replaceing a big string using different regular expressions (see some example at the end of the message). The problem is whenever I apply a "replace" it makes a new copy of string and I...
7
by: Tizzah | last post by:
What is wrong with that? regex = /^(http|https):\/\/+({1}+)*\.{2,5}(({1,5})?\/.*)?$/ if(field.hpage.value != regex.test(field.hpage.value)){ alert("Bad Homepage") field.hpage.focus()...
2
by: Helmut Jarausch | last post by:
Hi, sorry, this seems to be a FAQ but I couldn't find anything I need to check if an object is a compiled regular expression Say import re RX= re.compile('^something') how to test
15
by: Mark Rae | last post by:
Hi, I'm trying to construct a RegEx pattern which will validate a string so that it can contain: only the numerical characters from 0 to 9 i.e. no decimal points, negative signs, exponentials...
25
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.