473,666 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[2.5] Regex doesn't support MULTILINE?

Hello

I'm trying to extract information from a web page using the Re module,
but it doesn't seem to support MULTILINE:

=============
import re

#NO CRLF : works
response = "<b>Bla</b>blabla<font color=#123>"
#CRLF : doesn't work
response = "<b>Bla</b>blabla\r\n<fo nt color=#123>"

pattern = "<b>Bla</b>.+?<font color=(.+?)>"

p = re.compile(patt ern,re.IGNORECA SE|re.MULTILINE )
m = p.search(respon se)

if m:
print m.group(1)
else:
print "Not found"
=============

Do I need to add something else to have Re work as intended?

Thank you.
Jul 22 '07 #1
5 1856
On Sun, 2007-07-22 at 04:09 +0200, Gilles Ganault wrote:
Hello

I'm trying to extract information from a web page using the Re module,
That's your problem right there. RE is not the right tool for that job.
Use an actual HTML parser such as BeautifulSoup
(http://www.crummy.com/software/BeautifulSoup/) and your life will be
much easier.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Jul 22 '07 #2
On Sat, 21 Jul 2007 22:18:56 -0400, Carsten Haese
<ca*****@uniqsy s.comwrote:
>That's your problem right there. RE is not the right tool for that job.
Use an actual HTML parser such as BeautifulSoup
Thanks a lot for the tip. I tried it, and it does look interesting,
although I've been unsuccessful using a regex with BS to find all
occurences of the pattern.

Incidently, as far as using Re alone is concerned, it appears that
re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE
must be added.

Problem is, when I add re.DOTLINE, the search takes less than a second
for a 500KB file... and about 1mn30 for a file that's 1MB, with both
files holding similar contents.

Why such a huge difference in performance?

========= Using Re =============
import re
import time

pattern = "<span class=.?defaut. ?>(\d+:\d+).*? </span>"

pages = ["500KB.html","1 MB.html"]

#Veeeeeeeeeeery slow when parsing 1MB file !
p = re.compile(patt ern,re.IGNORECA SE|re.MULTILINE |re.DOTALL)
#p = re.compile(patt ern,re.IGNORECA SE|re.MULTILINE )

for page in pages:
f = open(page, "r")
response = f.read()
f.close()

start = time.strftime(" %H:%M:%S", time.localtime( time.time()))
print "before findall @ " + start
packed = p.findall(respo nse)
if packed:
for item in packed:
print item
=============== ============

Thank you.
Jul 22 '07 #3
On Jul 22, 7:56 am, Gilles Ganault <nos...@nospam. comwrote:
On Sat, 21 Jul 2007 22:18:56 -0400, Carsten Haese

<cars...@uniqsy s.comwrote:
That's your problem right there. RE is not the right tool for that job.
Use an actual HTML parser such as BeautifulSoup

Thanks a lot for the tip. I tried it, and it does look interesting,
although I've been unsuccessful using a regex with BS to find all
occurences of the pattern.

Incidently, as far as using Re alone is concerned, it appears that
re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE
must be added.

Problem is, when I add re.DOTLINE, the search takes less than a second
for a 500KB file... and about 1mn30 for a file that's 1MB, with both
files holding similar contents.

Why such a huge difference in performance?

pattern = "<span class=.?defaut. ?>(\d+:\d+).*? </span>"
That .*? can really slow it down if the following pattern
can't be found. It may end up looking until the end of the file for
proper continuation of the pattern and fail, and then start again.
Without DOTALL it would only look until the end of the line so
performance would stay bearable. Your 1.5MB file might have for
example
'<span class=defaut>13 :34< /span>'*10000 as its contents. Because
the < /spandoesn't match </span>, it would end up looking till
the end of the file for </spanand not finding it. And then move
on to the next occurence of '<span class=...' and see if it has better
luck finding a pattern there. That's an example of a situation where
the pattern matcher would become very slow. I'd have to see the 1.5MB
file's contents to better guess what goes wrong.

If the span's contents don't have nested elements (like <i></i>),
you could maybe use negated char range:

"<span class=.?default .?>(\d+:\d+)[^<]*</span>"

This pattern should be very fast for all inputs because the [^<]*
can't
match stuff indefinitely until the end of the file - only until the
next HTML element comes around. Or if you don't care about anything
but
those numbers, you should just match this:

"<span class=.?default .?>(\d+:\d+)"

Jul 22 '07 #4
En Sun, 22 Jul 2007 01:56:32 -0300, Gilles Ganault <no****@nospam. com>
escribió:
Incidently, as far as using Re alone is concerned, it appears that
re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE
must be added.

Problem is, when I add re.DOTLINE, the search takes less than a second
for a 500KB file... and about 1mn30 for a file that's 1MB, with both
files holding similar contents.

Why such a huge difference in performance?

pattern = "<span class=.?defaut. ?>(\d+:\d+).*? </span>"
Try to avoid using ".*" and ".+" (even the non greedy forms); in this
case, I think you want the scan to stop when it reaches the ending </span>
or any other tag, so use: [^<]* instead.

BTW, better to use a raw string to represent the pattern: pattern =
r"...\d+..."

--
Gabriel Genellina

Jul 22 '07 #5
On Sun, 22 Jul 2007 05:34:17 -0300, "Gabriel Genellina"
<ga*******@yaho o.com.arwrote:
>Try to avoid using ".*" and ".+" (even the non greedy forms); in this
case, I think you want the scan to stop when it reaches the ending </span>
or any other tag, so use: [^<]* instead.

BTW, better to use a raw string to represent the pattern: pattern =
r"...\d+..."
Thanks everyone for the help. It did improve things significantly :-)
Jul 24 '07 #6

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

Similar topics

0
1582
by: sinasalek | last post by:
i have a problem below code : <?php $text=' <html dir="rtl"> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html;
5
2138
by: Ali Eghtebas | last post by:
Hi, I've made this regex to catch the start of a valid multiline comment such as "/*" in e.g. T-SQL code. "(?<=^(?:*'*')*?*)(?<!^(?:*'*')*?--.*)/\*.*?$" With Multiline option on. As we know the T-SQL single line comment starts with a "--" and the string character is a "'". Considering all this, from these lines below the pattern will only catch "/*
2
1868
by: Mr.Clean | last post by:
I am working on modifying a syntax highlighter written in javascript and it uses several regexes. I need to add a language to the avail highlighters and need the following regexes modified to parse the new language, Delphi/Pascal. Source to the highlighter is avail here: http://www.dreamprojections.com/SyntaxHighlighter/Default.aspx ********************************************** COMMENTS
1
8997
by: David Elliott | last post by:
I have an expression that works for single line but not multiline. What am I missing? expression = "<div(?<data1>.*?)>(?<data2>.*?)</div>"; MatchCollection mc = Regex.Matches(data, expression, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); Expression works if data looks like this:
2
1648
by: Mortimer Schnurd | last post by:
Hi All, I am a VB 6 programmer who is now trying to learn C#. In doing so, I am trying to convert some of my VB modules to C#. I routinely user Reg Expressions in VB and am having some trouble trying to use Regex in C#. Basically, I have a fixed format text file which I need to validate prior to using in a program. The validation insures the data format matches what the program is expecting to find in the file. The pattern I am trying to...
6
2521
by: BigAl | last post by:
Perhaps someone here can help me out... RegEx: "^.*\d{5}(-\d{4})?.*$" Intended Purpose: To strip out the City/State/ZipCode line from a signature. Sample Text: Joe Jackson 131 W. 5th Street New York, NY 10023
5
10177
by: JackRazz | last post by:
Anyone know the regular expression to match a blank line where the byte sequence is "0D 0A 0D 0A" ive tried "\r\n\r\n+", "^$+" "\n\r" with no success. Any Ideas? Thanks - JackRazz This is the code fragment I'm trying Dim r As Regex, m As Match, i As Integer
5
5091
by: Chris | last post by:
How Do I use the following auto-generated code from The Regulator? '------------------------------------------------------------------------------ ' <autogenerated> ' This code was generated by a tool. ' Runtime Version: 1.1.4322.2032 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </autogenerated>
3
2279
by: Masa Ito | last post by:
I am trying to capture the contents of a function with Regex. I am using Expresso to test (nice - thanks for the great tool UltraPico!). I can handle my own with single line regex's (I think).. I want to have a named capture of the entire 'contents' of specific functions. EG: Sample code <Description("{0} is a required field.")_ Protected Overridable Function AccountIDRequired(ByVal target As Object, ByVal e As RuleArgs) As Boolean...
0
8356
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
8866
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...
1
8550
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,...
0
7385
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
6192
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
5663
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
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4366
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2011
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.