473,668 Members | 2,423 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using re.finditer()

I am still fairly new to Python and trying to learn to put RE's to good
use. I am a little confused about the finditer() method. It is documented
like so:

finditer( pattern, string)

Return an iterator over all non-overlapping matches for the RE pattern in
string. For each match, the iterator returns a match object. Empty matches
are included in the result unless they touch the beginning of another match.
New in version 2.2.
I would say this documentation is not quite right (or incomplete at
best) because it doesn't document any restriction about multiline matching,
but it certainly seems to have one. This would seem to be an ideal
application for finditer()...

#! /usr/bin/python

import re

html = """
<table>
<tr>
<td>Data 1-1</td>
<td>Data 1-2</td>
<td>Data 1-3</td>
</tr>
<tr>
<td>Data 2-1</td>
<td>Data 2-2
</td>
<td>Data 2-3</td>
</tr>
</table>
"""

pat = r'<td.*?>(.*?)</td>'
for match in re.finditer(pat , html):
print match.group(1)
The iterator returned seems to work fine to step through items that
happen to be contained within one line. That is, you can step through flat,
one-line td's, but if you want to step through tr's, this doesn't work (run
this code and notice Data 2-2 is not there). finditer() doesn't accept a
flag like re.DOTALL, as re.match() and re.search() do. It seems a shame not
to be able to put an otherwise smart design to use.

One work around to this is by applying a regualr RE like
'<tr.*?>(.*?)</tr>', finding the first match, and then chopping off the
found part as you go. Another is to change the pattern to something like:
pat = r'<td.*?>([\n\w\s\d-]*?)</td>' I guess I will get one of those
implemented and get this task done, but I am still interested in learning to
use RE's better.
Interestingly, using pat = r'<td.*?>([\r\n.]*?)</td>' does NOT work, and I
don't understand why - can someone explain that?
What exactly would be the equivalent set for dot with re.DOTALL turned on
([\w\W\r\n] works here, but does that really cover it)? Other ideas?

I can think of split & join substituion tricks & the like to replace \n
with something else, then put it back in, but that get's kinda messy and
requires you to find some special substitution character that's not
elsewhere. I want to apply this to dynamically generated text that I don't
control and keep this as general as possible. I'm wondering if I'm not
missing something here - is there no way to make finditer() work
(straightforwar dly) on multilines using just a simple dot RE?

Thanks for taking the time to read my post! :)

-ej
Jul 18 '05 #1
4 7643
Erik Johnson wrote:
pat = r'<td.*?>(.*?)</td>'
for match in re.finditer(pat , html):
printÂ*match.gr oup(1)
TheÂ*iteratorÂ* returnedÂ*seems Â*toÂ*workÂ*fin eÂ*toÂ*stepÂ*th roughÂ*itemsÂ*t hat
happen to be contained within one line. That is, you can step through
flat, one-line td's, but if you want to step through tr's, this doesn't
work (run this code and notice Data 2-2 is not there). finditer() doesn't
accept a flag like re.DOTALL, as re.match() and re.search() do. It seems a
shame not to be able to put an otherwise smart design to use.


There was a discussion on python-dev recently concerning "missing arguments"
in re.findall() and re.finditer(), see

http://mail.python.org/pipermail/pyt...er/048662.html

I think no change was made as there is already an alternative spelling:

r = re.compile(r'<t d.*?>(.*?)</td>', re.DOTALL)
for match in r.finditer(html ):
print match.group(1)

(or two, I didn't know about the option to embed flags in the string until
Robert Brewer's post).

Peter
Jul 18 '05 #2
Robert Brewer wrote:
Embed the flag(s) you desire in the regex itself. For example, to
include DOTALL, change r'<td.*?>(.*?)</td>' to r'(?s)<td.*?>(. *?)</td>'
Ahhhh! :) Sorry, my bad. Its right there in the docs, but I missed it -
haven't fully comprehended all of re yet. :)
Peter Otten wrote:
r = re.compile(r'<t d.*?>(.*?)</td>', re.DOTALL)
for match in r.finditer(html ):
print match.group(1)


Good - perhaps a more obvious way to do it.

So there's two good work-arounds.
Thank you both for your helpful replies! :)

I am still left puzzled though, why this won't work:

pat = r'<td.*?>([\n.]*?)</td>'
for match in re.finditer(pat , html):
print match.group(1)

but this will:

pat = r'<td.*?>([\w\W]*?)</td>'
for match in re.finditer(pat , html):
print match.group(1)

Thanks,
-ej
Jul 18 '05 #3
Erik Johnson wrote:
I am still left puzzled though, why this won't work:

pat = r'<td.*?>([\n.]*?)</td>'
for match in re.finditer(pat , html):
printÂ*match.gr oup(1)

re.findall(r"[.\n]", "\nx\n") ['\n', '\n'] re.findall(r"[.\n]", "\n.\n")

['\n', '.', '\n']

It seems a dot inside [] means a dot rather than "any character".

Peter
Jul 18 '05 #4

"Peter Otten" wrote in message news:cl******** *****@news.t-online.com...
re.findall(r"[.\n]", "\nx\n") ['\n', '\n'] re.findall(r"[.\n]", "\n.\n")

['\n', '.', '\n']

It seems a dot inside [] means a dot rather than "any character".


DOH! That's right in the docs too. <blush>

[]
Used to indicate a set of characters. Characters can be listed individually,
or a range of characters can be indicated by giving two characters and
separating them by a "-". Special characters are not active inside sets. For
example, [akm$] will match any of the characters "a", "k", "m", or "$";
[a-z] will match any lowercase letter, and [a-zA-Z0-9] matches any letter or
digit. Character classes such as \w or \S (defined below) are also
acceptable inside a range. If you want to include a "]" or a "-" inside a
set, precede it with a backslash, or place it as the first character. The
pattern []] will match ']', for example.
Like I said, I'm learning. Nothing like experience! :)
Thanks for your help!

-ej
Jul 18 '05 #5

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

Similar topics

0
1381
by: Robert Oschler | last post by:
I figured I'd utter some words of praise for re.finditer(). It's such a great feeling, when you come across a single statement that does everything you want in two lines of code: for g in re.finditer(pattern, string): do_something_to_g(g) In two lines of code I can break out all the sub-strings I need with a regular expressions pattern, and have each of them operated upon by a function.
8
2871
by: Chris Lasher | last post by:
Hello, I really like the finditer() method of the re module. I'm having difficulty at the moment, however, because finditer() still creates a callable-iterator oject, even when no match is found. This is undesirable in cases where I would like to circumvent execution of code meant to parse out data from my finditer() object. I know that if I place a finditer() object in an iterative for loop, the loop will not execute, but is there some...
6
3151
by: Erick | last post by:
Hello, I've been looking for a while for an answer, but so far I haven't been able to turn anything up yet. Basically, what I'd like to do is to use re.finditer to search a large file (or a file stream), but I haven't figured out how to get finditer to work without loading the entire file into memory, or just reading one line at a time (or more complicated buffering). For example, say I do this:
2
5919
by: rawCoder | last post by:
Hi All, I have a *.cer file, a public key of some one and I want to encrypt some thing using this public key. Can someone point me to a sample code for Encrypting some file using X509Certificate ( *.cer file ) so that it can be used to email as attachment. The real part is Encrypting using X509Certificate and CryptoServiceProvider.
15
17880
by: could ildg | last post by:
In re, the punctuation "^" can exclude a single character, but I want to exclude a whole word now. for example I have a string "hi, how are you. hello", I want to extract all the part before the world "hello", I can't use ".*" because "^" only exclude single char "h" or "e" or "l" or "o". Will somebody tell me how to do it? Thanks.
8
2709
by: John Pye | last post by:
Hi all I have a file with a bunch of perl regular expressions like so: /(^|)\*(.*?)\*(|$)/$1'''$2'''$3/ # bold /(^|)\_\_(.*?)\_\_(|$)/$1''<b>$2<\/ b>''$3/ # italic bold /(^|)\_(.*?)\_(|$)/$1''$2''$3/ # italic
3
1827
by: Gilles Ganault | last post by:
Hello I'd like to make sure there isn't an easier way to extract all the occurences found with re.finditer: ======================= req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() matches = re.compile("(\d+).html").finditer(response) # ----------- BEGIN
3
8272
by: JDeats | last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting and decrypting a file. http://support.microsoft.com/kb/307010 In .NET 2.0 this approach is not fully supported (a .NET 2.0 build with these methods, will appear to encrypt and decrypt, but the resulting decrypted file will be corrupted. I tried encrypting a .bmp file and then decrypting, the resulting decrypted file under .NET 2.0 is garbage, the .NET 1.1 build works...
2
3089
by: Fabian Braennstroem | last post by:
Hi, I would like to delete a region on a log file which has this kind of structure: #------flutest------------------------------------------------------------ 498 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04 8.3956e-04 3.8560e-03 4.8384e-02 11:40:01 499 499 1.0086e-03 2.4608e-04 9.8589e-05 1.4908e-04
0
8462
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8893
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
8658
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7405
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6209
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
5682
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();...
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1787
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.