473,626 Members | 3,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question regarding lists and regex

Here is a simple program, which queries /var/log/daemon on my OpenBSD box and
gets the list of valid ntp peers.

Questions:
what is the easiest way for me to create lists on the fly, by that I mean like perl

push my @foo, something_from_ say_stderr. The reason is as you can ip = [""]
statement before the for loop, I want to avoid that and use list within the
second ip loop, where I extract the ip address. Am I confusing?

regex: I presume this is rather a dumb question, anyways here it comes! as you
can see from my program, pattIp = r\d{1,3}\.... etc, is there any other easy way
to group the reptitions, instead of typing the same regex 4 times.

TIA
Prabhu
-

amazon: [~/working/programs/python/regex]
ttyp4: [109]$ cat syslog.py
#!/usr/bin/env python
# $Id: syslog.py,v 1.6 2006/11/09 06:24:03 pgurumur Exp $

import getopt, re, os, string, sys, time
(dirname, program) = os.path.split(s ys.argv[0])
argc = len(sys.argv)

def usage():
print program + ": options"
print "options: "
print " --filename | -f [ name of the file ]"
print " --help | -h [ prints this help ]"
sys.exit(1)

if __name__ == "__main__":
if (argc <= 1):
usage()
else:
try:
opts, args = getopt.getopt(s ys.argv[1:], "f:h", ["help", "filename="])
except getopt.GetoptEr ror:
usage()
else:
filename = ""
for optind, optarg in opts:
if optind in ("-f", "--filename"):
filename = optarg
elif optind in ("-h", "--help"):
usage()

if len(filename):
fh = 0
try:
fh = open(filename, "r")
except IOError, (error, message):
print program + ": cannot open " + filename + ": " + message
sys.exit(1)

pattNtp = r'.*ntpd(?=.*no w\s+valid)'
count = 0
ip = [""]
pid = 0
for line in fh.readlines():
if re.match(pattNt p, line.strip(), re.IGNORECASE):
string = line.strip()
pattPid = r'\[\d{1,5}\]'
pidMatch = re.search(pattP id, string, re.IGNORECASE)
if pidMatch is not None:
pid = int(re.sub(r'\[|\]', "", pidMatch.group( )))

pattIp = r'\d{1,3}\.\d{1 ,3}\.\d{1,3}\.\ d{1,3}'
match = re.search(pattI p, string, re.IGNORECASE)
if match is not None:
ip.append(match .group())
count += 1

print "NTP program started with pid:", pid
print "Number of valid peers:", count
for x in ip:
if len(x):
print x

fh.close()
Nov 9 '06 #1
2 1175
"Prabhu Gurumurthy" <pg******@gmail .comwrote in message
news:ma******** *************** *************** *@python.org...
Here is a simple program, which queries /var/log/daemon on my OpenBSD box
and gets the list of valid ntp peers.

Questions:
what is the easiest way for me to create lists on the fly, by that I mean
like perl

push my @foo, something_from_ say_stderr. The reason is as you can ip =
[""] statement before the for loop, I want to avoid that and use list
within the second ip loop, where I extract the ip address. Am I confusing?
Typically, one initializes a list to be empty, that is [], not [""]. Python
will not read your mind at append time and think "oh! we're appending to a
list and we forgot to create one in the first place, let's make one now." I
guess Perl allows this, but the clarity of including the initialization
statement overrules the convenience of leaving it out.
regex: I presume this is rather a dumb question, anyways here it comes! as
you can see from my program, pattIp = r\d{1,3}\.... etc, is there any
other easy way to group the reptitions, instead of typing the same regex 4
times.
Here's one way, tested at the Python command line:
>>print r'\.'.join( [r'\d{1,3}']*4 )
\d{1,3}\.\d{1,3 }\.\d{1,3}\.\d{ 1,3}

This avoids the pattern duplication, but I think using join is much less
easily recognized as a pattern for an IP address.
TIA
Prabhu
Some other comments/free advice:
1. I was curious about this line:
pid = int(re.sub(r'\[|\]', "", pidMatch.group( )))
You already know pidMatch.group( ) is going to start with a '[', followed by
an integer string, and end with a ']', otherwise it wouldn't have matched
pidPatt. Instead of whacking this with another re-type call, how about just
some simple string slicing:
pid = pidMatch.group( )[1:-1]

2. No real need to keep count of the found ip's, just use len(ip) to tell
you how many entries there are in the list (especially once you convert to
intializing with an empty list).

3. Similarly, you'll be able to remove the 'if len(x)' test when printing
out the contents of the ip list if you init with [] instead of [""]. Also,
the Python idiom for testing if x is the empty string is usually just 'if
x', not 'if len(x)'.

-- Paul
Nov 9 '06 #2
Ant


On Nov 9, 6:29 am, Prabhu Gurumurthy <pguru...@gmail .comwrote:
....
regex: I presume this is rather a dumb question, anyways here it comes! as you
can see from my program, pattIp = r\d{1,3}\.... etc, is there any other easy way
to group the reptitions, instead of typing the same regex 4 times.
....
pattIp = r'\d{1,3}\.\d{1 ,3}\.\d{1,3}\.\ d{1,3}'
pattIp = r"\d{1,3}(\.\d{ 1,3}){3}"

Is the best you can get using pure regexes (rather than something like
Paul's solution).

Nov 9 '06 #3

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

Similar topics

9
3744
by: Dave H | last post by:
Hello, I have a query regarding definition lists. Is it good practice semantically to use the dt and dd elements to mark up questions and answers in a frequently asked questions list, or FAQ? Here is an example of just such a usage: <dl class="faq"> <di>
5
5395
by: Seth | last post by:
I can't get this thing made for the life of me. I've gone through every step per the Boost website regarding using bjam. Nothing. Can anyone give any advice or are there pre-made boost hpps for Windows platform? thanks in advance seth
10
1863
by: bullockbefriending bard | last post by:
first, regex part: I am new to regexes and have come up with the following expression: ((1|),(1|)/){5}(1|),(1|) to exactly match strings which look like this: 1,2/3,4/5,6/7,8/9,10/11,12 i.e. 6 comma-delimited pairs of integer numbers separated by the
46
3402
by: junky_fellow | last post by:
Hi, Is there any efficient way of finding the intesection point of two singly linked lists ? I mean to say that, there are two singly linked lists and they meet at some point. I want to find out the addres of the node where the two linked intersect. thanks for any help...
0
8202
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8707
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8641
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8366
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6125
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4202
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1812
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1512
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.