473,489 Members | 2,492 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

regular expressions and matches

Hello,

I have recently written a small function that will verify that an IP
address is valid.

==SNIP==

import re
ipAddress = raw_input('IP Address : ')

def validateIP(ipAddress):
ipRegex =
r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$"
re_ip = re.compile(ipRegex)
match = re_ip.match(ipAddress)
if not match:
print "an error has occured with ipAddress"
return match
else:
return match

print(validateIP(ipAddress))

==SNIP==

I was having issues trying to get my code working so that I could pass
the IP addresses and it would return a true or false. When it matches I
get something that looks like this.

python ip_valid.py
IP Address : 192.158.1.1
<_sre.SRE_Match object at 0xb7de8c80>

As I am still attempting to learn python I am interested to know how I
could get the above to return a true or false if it matches or does not
match the IP address. I would also like to expand that so that if the
IP is wrong it requests the IP address again and recalls the function.
I have done the same thing in php very easily but python appears to be
getting the better of me. Any assistance and advice would be greatly
appreciated.

Regards,

Johhny

Mar 30 '06 #1
3 1523
"Johhny" wrote:
I was having issues trying to get my code working so that I could pass
the IP addresses and it would return a true or false. When it matches I
get something that looks like this.

python ip_valid.py
IP Address : 192.158.1.1
<_sre.SRE_Match object at 0xb7de8c80>

As I am still attempting to learn python I am interested to know how I
could get the above to return a true or false if it matches or does not
match the IP address.


you can use the return value right away. the match function/method
returns None if it fails to find a match, and None is treated as a false
value in a "boolean context":

http://docs.python.org/ref/Booleans.html

if you get a match instead, you get a match object (SRE_Match),
which is treated as True.

if you really really really want to return True or False, you can do

result = bool(re.match(...))

</F>

Mar 30 '06 #2
Johhny wrote:
Hello,

I have recently written a small function that will verify that an IP
address is valid.
(snip re.match() based solution - just one remark: compiling the regexp
on each function call is more than useless)
I was having issues trying to get my code working so that I could pass
the IP addresses and it would return a true or false. When it matches I
get something that looks like this.

python ip_valid.py
IP Address : 192.158.1.1
<_sre.SRE_Match object at 0xb7de8c80>

As I am still attempting to learn python I am interested to know how I
could get the above to return a true or false if it matches or does not
match the IP address.
If you re-read the fine manual, you'll notice that re.match() returns
either None or a Match object. Since, in a boolean context, None evals
to False and a Match object to True, just convert the return of re.match
to a boolean:

return bool(re_ip.match(ipAddress))

BTW, don't mix outputs and a logic. Your validateIp() function should
*only* validate, not print anything (except for debugging purpose, but
then it should either go to a log or at least to stderr, stdout is for
normal program outputs).
I would also like to expand that so that if the
IP is wrong it requests the IP address again and recalls the function.
Then wrap the raw_input()/validateIp() into a loop. And wrap this loop
into a function !-)

def get_valid_ip(prompt="please enter an ip",
errormsg="Sorry, %s is not a valid ip"):
while True:
ip = raw_input("%s : " % prompt).strip()
if validateIp(ip):
return ip
else:
print errormsg % ip

ip = get_valid_ip()

I have done the same thing in php very easily but python appears to be
getting the better of me.


Knowledge doesn't map one-to-one from one language to another.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Mar 30 '06 #3

Johhny wrote:
Hello,

I have recently written a small function that will verify that an IP
address is valid.

==SNIP==

import re
ipAddress = raw_input('IP Address : ')

def validateIP(ipAddress):
ipRegex =
r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$"
Good lord! You might as well be writing in assembly! The re module
docs should include a customer warning label.

Regular expressions are not the answer here. Probably 80% of the regex
virus could be stamped out if people used split instead. How about
something simpler, like this:

def ipValid(ipAddress):
dots = ipAddress.split(".")
if len(dots) != 4:
return False
for item in dots:
if not 0 <= int(item) <= 255:
return False
return True

....although even this function (like yours) will declare as "valid" an
IP address like 0.255.0.0.

For a real-world application, how about:

import socket
try:
mm = socket.inet_aton(ipAddress)
return True # We got through that call without an error, so it is
valid
except socket.error:
return False # There was an error, so it is invalid

re_ip = re.compile(ipRegex)
match = re_ip.match(ipAddress)
if not match:
print "an error has occured with ipAddress"
return match
else:
return match

print(validateIP(ipAddress))

==SNIP==

I was having issues trying to get my code working so that I could pass
the IP addresses and it would return a true or false. When it matches I
get something that looks like this.

python ip_valid.py
IP Address : 192.158.1.1
<_sre.SRE_Match object at 0xb7de8c80>

As I am still attempting to learn python I am interested to know how I
could get the above to return a true or false if it matches or does not
match the IP address. I would also like to expand that so that if the
IP is wrong it requests the IP address again and recalls the function.
I have done the same thing in php very easily but python appears to be
getting the better of me. Any assistance and advice would be greatly
appreciated.

Regards,

Johhny


Mar 30 '06 #4

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

Similar topics

7
2569
by: YoBro | last post by:
Hi I have used some of this code from the PHP manual, but I am bloody hopeless with regular expressions. Was hoping somebody could offer a hand. The output of this will put the name of a form...
1
4154
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make...
1
3239
by: André Søreng | last post by:
With the re/sre module included with Python 2.4: pattern = "(?P<id1>avi)|(?P<id2>avi|mp3)" string2match = "some string with avi in it" matches = re.finditer(pattern, string2match) .......
11
3857
by: Martin Robins | last post by:
I am trying to parse a string that is similar in form to an OLEDB connection string using regular expressions; in principle it is working, but certain character combinations in the string being...
1
2033
by: Daniel Walzenbach | last post by:
Hi, does anybody know I can extract a substring of a text with regular expressions. Let’s consider the following text: “Regular expressions are often used to make sure that a string matches a...
9
3337
by: Pete Davis | last post by:
I'm using regular expressions to extract some data and some links from some web pages. I download the page and then I want to get a list of certain links. For building regular expressions, I use...
25
5128
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...
3
2525
by: Chris | last post by:
Hi everyone, I'm trying to parse through the contents of some text files with regular expressions, but am new to regular expressions and how to use them in VB.net. I'm pretty sure that the...
3
2733
by: Zeba | last post by:
Hi guys, I need some help regarding regular expressions. Consider the following statement : System.Text.RegularExpressions.Match match =...
1
4359
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find...
0
7108
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
6967
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
7142
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,...
1
6847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7352
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...
1
4875
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3071
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
618
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.