473,594 Members | 2,794 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 #1
26 2368

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)


Why not something like

import re
string = 'ababababababab ab'
pattern = re.compile(r"^a ba")
ans = []
for x in xrange(len(stri ng)):
m = pattern.match(s tring[x:])
if m: ans.append( (x+m.start(),x+ m.end()))

# now ans is a list of pairs (p,q) where the substring string[p:q]
matches pattern

- Murali

May 10 '06 #2
John Salerno 写道:
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)')
Below from the python library reference

*|(?=...)|*
Matches if ... matches next, but doesn't consume any of the string.
This is called a lookahead assertion. For example, Isaac (?=Asimov)
will match |'Isaac '| only if it's followed by |'Asimov'|.
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.

I try the code , but I give seven results ! 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 #3
Right about now somebody usually jumps in and shows you how to do this
without using regex and using string methods instead.

I'll watch.

rd

May 10 '06 #4
Bo Yang wrote:
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.

I try the code , but I give seven results !


Sorry, I meant that findall() only returns 4 results when searching for
'aba', when there are actually seven instances of 'aba'. This doesn't
involve the look-ahead RE.
May 10 '06 #5
BartlebyScriven er wrote:
Right about now somebody usually jumps in and shows you how to do this
without using regex and using string methods instead.

I'll watch.

rd


Heh heh, I'm sure you're right, but this is more just an exercise for me
in REs, so I'm curious how you might do it, unless the answer is that
it's just too complicated to be worth it (like Murali's example!) That
goes beyond just an RE pattern.
May 10 '06 #6
I have to at least try :)

s = "ababababababab ab"

for x in range(len(s)):
.... try:
.... s.index("aba", x, x + 3)
.... except ValueError:
.... pass

rd

May 10 '06 #7
BartlebyScriven er wrote:
I have to at least try :)

s = "ababababababab ab"

for x in range(len(s)):
... try:
... s.index("aba", x, x + 3)
... except ValueError:
... pass

rd


yeah, looks like index() or find() can be used to do it instead of RE,
but still, i'd like to know if there's a way you can write an RE
expression to do it (and just an RE expression, without all the other
for loops and extra nonsense...othe rwise i might as well just use string
methods)
May 10 '06 #8
>From the Python 2.4 docs:

findall( pattern, string[, flags])
Return a list of all ***non-overlapping*** matches of pattern in
string....

By design, the regex functions return non-overlapping patterns.

Without doing some kind of looping, I think you are out of luck.

If you pattern is fixed, then a solution might be:
string = 'ababababababab ab'
pat = 'aba'
[pat for s in re.compile('(?= '+pat+')').find all(string)] ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']

If the pattern is not fixed (i.e. 'a.a') then this method can still get
a count of overlapping matches, but cannot get the individual match
strings themselves.

A simple loop should do in this case, though:
for i in range(len(strin g)):

.... r= re.match(pat,st ring[i:])
.... if r: print r.group()
....
aba
aba
aba
aba
aba
aba
aba

May 10 '06 #9
>> otherwise i might as well just use string
methods


I think you're supposed to use string methods if you can, to avoid the
old adage about having two problems instead of one when using regex.

rd

May 10 '06 #10

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

Similar topics

8
6974
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
2186
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
1481
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
4299
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
1590
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
1775
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
4819
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
2488
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
1331
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
7946
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8372
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
8003
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
8234
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
6654
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 projectplanning, coding, testing, and deploymentwithout 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...
0
3897
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2385
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
1
1478
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1210
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.