2

I basically want the same functionality of preg_match_all()from PHP in a Python way.

If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?

Example:

s = "supercalifragilisticexpialidocious"

Would return:

{
  'u' : 1,
  'e' : 3,
  'a' : 6,
  'i' : 8,
  'a' : 11,
  'i' : 13,
  'i' : 15
}

3 Answers 3

6

You can do this faster without regexp

[(x,i) for i,x in enumerate(s) if x in "aeiou"]

Here are some timings:
For s = "supercalifragilisticexpialidocious"

timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
10000 loops, best of 3: 27.5 µs per loop

timeit [(x,i) for i,x in enumerate(s) if x in "aeiou"]
100000 loops, best of 3: 14.4 µs per loop

For s = "supercalifragilisticexpialidocious"*100

timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
100 loops, best of 3: 2.01 ms per loop

timeit [(x,i) for i,x in enumerate(s) if x in "aeiou"]
1000 loops, best of 3: 1.24 ms per loop
Sign up to request clarification or add additional context in comments.

Comments

5

What you ask for can't be a dictionary, since it has multiple identical keys. However, you can put it in a list of tuples like this:

>>> [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)]
[('u', 1), ('e', 3), ('a', 6), ('i', 8), ('a', 11), ('i', 13), ('i', 15), ('i', 18), ('e', 20), ('i', 23), ('a', 24), ('i', 26), ('o', 28), ('i', 30), ('o', 31), ('u', 32)]

Comments

0

Like this, for example:

import re

def findall(pattern, string):
    res = {}
    for match in re.finditer(pattern, string):
        res[match.group(0)] = match.start()
    return res

print findall("[aeiou]", "Test this thang")

Note that re.finditer only finds non-overlapping matches. And the dict keys will be overwritten, so if you want the first match, you'll have to replace the innermost loop by:

    for match in re.finditer(pattern, string):
        if match.group(0) not in res: # <-- don't overwrite key
            res[match.group(0)] = match.start()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.