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. 26 2383
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
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.
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
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.
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.
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
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)
>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
>> 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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...
|
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
|
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...
|
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)
| |
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
|
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...
|
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;
|
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...
|
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...
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
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...
|
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();...
| |
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...
| |