473,796 Members | 2,515 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reusing parts of a string in RE matches?

I probably should find an RE group to post to, but my news server at
work doesn't seem to have one, so I apologize. But this is in Python
anyway :)

So my question is, how can find all occurrences of a pattern in a
string, including overlapping matches? I figure it has something to do
with look-ahead and look-behind, but I've only gotten this far:

import re
string = 'ababababababab ab'
pattern = re.compile(r'ab (?=a)')
m = pattern.findall (string)

This matches all the 'ab' followed by an 'a', but it doesn't include the
'a'. What I'd like to do is find all the 'aba' matches. A regular
findall() gives four results, but really there are seven.

Is there a way to do this with just an RE pattern, or would I have to
manually add the 'a' to the end of the matches?

Thanks.
May 10 '06
26 2386
Mirco Wahab wrote:
Py:
import re
tx = 'a1a2a3A4a35a6b 7b8c9c'
rg = r'(\w)(?=(.\1)) '
print re.findall(rg, tx)


The only problem seems to be (and I ran into this with my original
example too) that what gets returned by this code isn't exactly what you
are looking for, i.e. the numbers '1', '2', etc. You get a list of
tuples, and the second item in this tuple contains the number, but also
the following \w character.

So there still seems to be some work that must be done when dealing with
overlapping patterns/look-ahead/behind.

Oh wait, a thought just hit me. Instead of doing it as you did:

rg = r'(\w)(?=(.\1)) '

Could you do:

rg = r'(\w)(?=(.)\1) '

That would at least isolate the number, although you'd still have to get
it out of the list/tuple.
May 11 '06 #21
Hi John
rg = r'(\w)(?=(.)\1) '

That would at least isolate the number, although you'd still have to get
it out of the list/tuple.


I have no idea how to do this
in Python in a terse way - but
I'll try ;-)

In Perl, its easy. Here, the
"match construct" (\w)(?=(.)\1)
returns all captures in a
list (a 1 a 2 a 4 b 7 c 9)
because we capture 2 fields per
comparision:
The first is (\w), needed for
backreference, the second is
the dot (.), which finds the
number in the center (or any-
thing else).

So, in perl you 'filter' by the
'grep' function on each list
element: grep{ /\d/ } - this
means, only numbers (\d) will
pass through:

$_ = 'a1a2a3Aa4a35a6 b7b8c9c';
print grep{/\d/} /(\w)(?=(.)\1)/g;
#prints => 1 2 4 7 9

I'll try to fiddle somthing out
that works in Python too ...

Regards

M.
May 11 '06 #22
Mirco Wahab wrote:
I have no idea how to do this
in Python in a terse way - but
I'll try ;-)

In Perl, its easy. Here, the
"match construct" (\w)(?=(.)\1)
returns all captures in a
list (a 1 a 2 a 4 b 7 c 9)


Ah, I see the difference. In Python you get a list of tuples, so there
seems to be a little extra work to do to get the number out.
May 11 '06 #23
Hi John
Ah, I see the difference. In Python you get a list of tuples, so there
seems to be a little extra work to do to get the number out.


Dohh, after two cups of coffee
ans several bars of chocolate
I eventually mad(e) it ;-)

In Python, you have to deconstruct
the 2D-lists (here: long list of
short lists [a,2] ...) by
'slicing the slice':

char,num = list[:][:]

in a loop and using the apropriate element then:

import re

t = 'a1a2a3Aa4a35a6 b7b8c9c';
r = r'(\w)(?=(.)\1) '
l = re.findall(r, t)

for a,b in (l[:][:]) : print b

In the moment, I find this syntax
awkward and arbitary, but my mind
should change if I'm adopted more
to this in the end ;-)

Regards,

M.
May 11 '06 #24
Hi John
Ah, I see the difference. In Python you get a list of
tuples, so there seems to be a little extra work to do
to get the number out.


Dohh, after two cups of coffee
ans several bars of chocolate
I eventually mad(e) it ;-)

In Python, you have to deconstruct
the 2D-lists (here: long list of
short lists [a,2] ...) by
'slicing the slice':

char,num = list[:][:]

in a loop and using the apropriate element then:

import re

t = 'a1a2a3Aa4a35a6 b7b8c9c';
r = r'(\w)(?=(.)\1) '
l = re.findall(r, t)

for a,b in l : print b

(l sould implicitly be decoded
sequentially as l[:][->a : ->b]
in the loop context.)

In the moment, I find this syntax
somehow hard to remember, but my
mind should change if I'm adopted
more to this in the end ;-)

Regards,

M.
May 11 '06 #25
Mirco Wahab wrote:
In Python, you have to deconstruct
the 2D-lists (here: long list of
short lists [a,2] ...) by
'slicing the slice':

char,num = list[:][:]

in a loop and using the apropriate element then:

import re

t = 'a1a2a3Aa4a35a6 b7b8c9c';
r = r'(\w)(?=(.)\1) '
l = re.findall(r, t)

for a,b in (l[:][:]) : print b

In the moment, I find this syntax
awkward and arbitary, but my mind
should change if I'm adopted more
to this in the end ;-)


in contemporary Python, this is best done by a list comprehension:

l = [m[1] for m in re.findall(r, t)]

or, depending on what you want to do with the result, a generator
expression:

g = (m[1] for m in re.findall(r, t))

or

process(m[1] for m in re.findall(r, t))

if you want to avoid creating the tuples, you can use finditer instead:

l = [m.group(2) for m in re.finditer(r, t)]
g = (m.group(2) for m in re.finditer(r, t))

finditer is also a good tool to use if you need to do more things with
each match:

for m in re.finditer(r, t):
s = m.group(2)
... process s in some way ...

the code body will be executed every time the RE engine finds a match,
which can be useful if you're working on large target strings, and only
want to process the first few matches.

for m in re.finditer(r, t):
s = m.group(2)
if s == something:
break
... process s in some way ...

</F>

May 12 '06 #26
Hi Fredrik

you brought up some terse and
somehow expressive lines with
their own beauty ...
[this] is best done by a list comprehension:
l = [m[1] for m in re.findall(r, t)]

or, [...] a generator expression:
g = (m[1] for m in re.findall(r, t))

or
process(m[1] for m in re.findall(r, t))

... avoid creating the tuples, ... finditer instead:
l = [m.group(2) for m in re.finditer(r, t)]
g = (m.group(2) for m in re.finditer(r, t))

finditer is also a good tool to use
for m in re.finditer(r, t):
s = m.group(2)
... process s in some way ...


.... which made me wish to internalize such wisdom too ;-)

This looks almost beautiful, it made me stand up and
go to some large book stores in order to grab a good
book on python.

Sadly, there were none (except one small 'dictionary',
ISBN: 3826615123). I live in a fairly large city
in Germany w/three large bookstores in the center,
where one can get loads of PHP and Java books, lots
of C/C++ and the like - even some Ruby books (some
"Rails" too) on display (WTF).

Not that I wouldn't order books (I do that all the
time for 'original versions') but it makes one
sad-faced to see the small impact of the Python
language here today on bookstore-tournarounds ...

Thanks & regards

Mirco
May 13 '06 #27

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

Similar topics

8
6987
by: Eric Linders | last post by:
Hi, I'm trying to figure out the most efficient method for taking the first character in a string (which will be a number), and use it as a variable to check to see if the other numbers in the string match that first number. I'm using this code for form validation of a telephone number. Previous records from the past few months show that when someone is just messing around on one of our forms (to waste our time), they type
3
2196
by: Piet | last post by:
Hello, I have a very strange problem with regular expressions. The problem consists of analyzing the properties of columns of a MySQL database. When I request the column type, I get back a string with the following composition: vartype(width|list) further variable attributes. vartype is a simple string(varchar, tinyint ...) which might be followed by a string in curved brackets. This bracketed string is either composed of a single...
14
1500
by: SnakeS | last post by:
Hi, I want modify a string as "112233445566" in "11:22:33:44:55:66" which is the best method? Using a RegExp? and if yes how? Thanks in advance
29
4325
by: zoro | last post by:
Hi, I am new to C#, coming from Delphi. In Delphi, I am using a 3rd party string handling library that includes some very useful string functions, in particular I'm interested in BEFORE (return substring before a pattern), AFTER (return substring after a pattern), and BETWEEN (return substring between 2 patterns). My questions are: 1. Can any tell me how I can implement such functionality in C#? 2. Is it possible to add/include function...
3
1607
by: mehdi_mousavi | last post by:
Hi folks, Consider the following JavaScript function: function removeParam(str, name) { var rgx = new RegExp('(' + name + '=\\w*)|(' + name + '=\\w*;)'); rgx.global = true; rgx.ignoreCase = true; var matches = rgx.exec(str); if(matches == null)
1
1783
by: Jen | last post by:
..NET 2.0 introduced the <connectionStrings> section in .config files, but how do I reuse the connection strings defined under <connectionStrings> in other parts of the config files? <connectionStrings> <add name="connStr1" .../> </connectionStrings> Now I want to reuse the connection string defined by the name "connStr1" in 25 other places in the same configuration file by
24
4853
by: garyusenet | last post by:
I'm working on a data file and can't find any common delimmiters in the file to indicate the end of one row of data and the start of the next. Rows are not on individual lines but run accross multiple lines. It would appear though that every distinct set of data starts with a 'code' that is always the 25 characters long. The text is variable however. Assuming i've read the contents of the file into the string myfile, how do i split my...
8
2497
by: bill | last post by:
Turning on error_reporting(E_ALL); was quite an eye opener as to how much "fixing" PHP will do for the sloppy coder. I fixed all of the errors except: Notice: Undefined property: parts in /ContactManagement/contact_mainpage.php on line 120 where the line in question is: $parts = $struct->parts;
0
1337
by: itfetish | last post by:
We have a web parts intranet at our office here I have been working on. I have been trying to create a way of getting our OCE TDS 600 plotter queue to be a web part on the page, seeing as their is no way of interfacing apart from their 'print exec workgroup' web based program. So I decided to screen scrape, I've done a scrape of the intranet page of print exec workgroup (http://tds600 on our network) seemed to go fine, then i used...
0
9529
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
10457
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
10231
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
10176
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
9054
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
7550
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
6792
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
5443
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
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.