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?
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?
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
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)
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
> 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
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
Thanks, Ben. Quite an education!
rick
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
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! :) 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, 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...
|
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: 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: 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...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |