473,796 Members | 2,661 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 2387
mp*******@gmail .com wrote:
string = 'ababababababab ab'
pat = 'aba'
[pat for s in re.compile('(?= '+pat+')').find all(string)]

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']


Wow, I have no idea how to read that RE. First off, what does it match?
Should something come before the parentheses, and that will be what
matches? Also, what are the '+'s doing? Are they literal +s or still
being used as RE syntax?
May 10 '06 #11
John Salerno wrote:
mp*******@gmail .com wrote:
> string = 'ababababababab ab'
> pat = 'aba'
> [pat for s in re.compile('(?= '+pat+')').find all(string)]

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']


Wow, I have no idea how to read that RE. First off, what does it match?
Should something come before the parentheses, and that will be what
matches? Also, what are the '+'s doing? Are they literal +s or still
being used as RE syntax?


Nevermind, I get it! The point is that you *aren'* matching anything
(except the empty string), and this only to see how many times it
occurs, then you are replacing those occurrences with the pattern
string. So this is basically like a counter?
May 10 '06 #12
John Salerno wrote:
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?


You can specify a start location to re.search(), and get the location of
a match from a match object. This allows you to loop, searching the
string following the last match:

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

ans = []
start = 0
while True:
m = pattern.search( string, start)
if not m: break
ans.append( (m.start(), m.end()) )
start = m.start() + 1

print ans # => [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12), (12, 14)]

Kent
May 10 '06 #13
Exactly,

Now this will work as long as there are no wildcards in the pattern.
Thus, only with fixed strings. But if you have a fixed string, there
is really no need to use regex, as it will complicate you life for no
real reason (as opposed to simple string methods).

With a more complex pattern (like 'a.a': match any character between
two 'a' characters) this will get the length, but not what character is
between the a's.

To actually do that you will need to iterate through the string and
apply the pattern match (which matches only the beginning of a string)
to a indexed subset of the original (see example in the last post)

May 10 '06 #14
John Salerno wrote:
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?


Yes, and no extra for loops are needed! You can define groups inside
the lookahead assertion:
import re
re.findall(r'(? =(aba))', 'ababababababab ab')

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']

--Ben

May 11 '06 #15
> Yes, and no extra for loops are needed! You can define groups inside
the lookahead assertion:
>>> import re
>>> re.findall(r'(? =(aba))', 'ababababababab ab')

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']


Wonderful and this works with any regexp, so

import re

def all_occurences( pat,str):
return re.findall(r'(? =(%s))'%pat,str )

all_occurences( "a.a","abacadab cda") returns ["aba","aca","ad a"] as
required.

- Murali

May 11 '06 #16
Murali wrote:
Yes, and no extra for loops are needed! You can define groups inside
the lookahead assertion:
>>> import re
>>> re.findall(r'(? =(aba))', 'ababababababab ab')

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']


Wonderful and this works with any regexp, so

import re

def all_occurences( pat,str):
return re.findall(r'(? =(%s))'%pat,str )

all_occurences( "a.a","abacadab cda") returns ["aba","aca","ad a"] as
required.

Careful. That won't work as expected for *all* regexps. Example:
import re
re.findall(r'(? =(a.*a))', 'abaca') ['abaca', 'aca']

Note that this does *not* find 'aba'. You might think that making it
non-greedy might help, but:
re.findall(r'(? =(a.*?a))', 'abaca')

['aba', 'aca']

Nope, now it's not finding 'abaca'.

This is by design, though. From
http://www.regular-expressions.info/lookaround.html (a good read, by
the way):

"""As soon as the lookaround condition is satisfied, the regex engine
forgets about everything inside the lookaround. It will not backtrack
inside the lookaround to try different permutations."" "

Moral of the story: keep lookahead assertions simple whenever
possible. :-)

--Ben

May 11 '06 #17
Thanks, Ben. Quite an education!

rick

May 11 '06 #18
Hi mpeters42 & John
With a more complex pattern (like 'a.a': match any character between
two 'a' characters) this will get the length, but not what character is
between the a's.


Lets take this as a starting point for another example
that comes to mind. You have a string of characters
interspersed with numbers: tx = 'a1a2a3A4a35a6b 7b8c9c'

Now you try to find all _numbers_, which have
symmetrical characters (like a<-2->a) which
are not in 3/3/3... synced groups.

This can easy be done in P(ytho|nerl) etc. by
positive lookahead (even the same pattern does:)
Py:
import re
tx = 'a1a2a3A4a35a6b 7b8c9c'
rg = r'(\w)(?=(.\1)) '
print re.findall(rg, tx)
Pe:
$_ = 'a1a2a3A4a35a6b 7b8c9c';
print /(\w)(?=(.)\1)/g;

(should find 1,2,7,9 only, python regex
written to var in order to prevent
clunky lines ;-)

BTW, Py Regex Engine seems to
be very close to the perl one:
Naive (!) matching of a pattern
with 14 o's (intersperded by
anything) against a string of
16 o's takes about exaclty the same
time here in Py(2.4.3) and Pe (5.8.7):

tl = 'oooooooooooooo oo'
rg = r'o*o*o*o*o*o*o *o*o*o*o*o*o*o*[\W]'
print re.search(rg, tl)

Py: 101 sec
Pe: 109 sec

(which would find no match because there's
no \W-like character at the end of the
string here)

Regards

Mirco
May 11 '06 #19
Ben Cartwright wrote:
Yes, and no extra for loops are needed! You can define groups inside
the lookahead assertion:
>>> import re
>>> re.findall(r'(? =(aba))', 'ababababababab ab')

['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']


Wow, that was like magic! :)
May 11 '06 #20

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
1501
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
1784
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
9684
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
9530
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
10459
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
10182
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
10017
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
6793
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
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
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
3
2928
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.