Ok, I would like to use a regular expression that I create dynamically to search and replace words in a file. For instance:


import re
fl = re.compile('abc|def|ghi')
ts = 'xyz abc mno def'

n = fl.search(ts)

print n

How would I find all matches in the string? So far, "n" only returns the first occurence.

Or, maybe I'm going about this wrong anyway. What I would like to do is find each match that is in my re:compile, and replace it with additional text appended to that match. So, my text string would end up being 'xyz match=abc mno match=def', as 'abc' and 'def' are items in my re. In my real world example, my re:compile string is created dynamically and will have anywhere from 10 to 50 items (this part of the code works fine), but I'm having a hard time making a one to one relationship with the item in the re:compile with what is actually found. Since regular expressions are supposed to be fast, I didn't explore using a loop yet, but maybe that's the only way. Advice?

Recommended Answers

All 3 Replies

You are better off doing it this way and then process the resulting list ...

import re

fl = re.compile('(abc|def|ghi)')
ts = 'xyz abc mno def'

q = fl.findall(ts)

print q  # ['abc', 'def']

For a straight replace ...

import re

fl = re.compile('(abc|def|ghi)')
ts = 'xyz abc mno def'

ms = fl.sub('zzz', ts)

print ms  # xyz zzz mno zzz

Thanks very much. The fl.sub works like a charm.

But, how can I append the item that I am searching for with the replacement text? For instance, instead of "xyz zzz mno zzz" as a result, I would like "xyz abczzz mno defzzz".

In this case you are better off to use just Python. Actually, regular expressions aren't necessarily faster. I added plenty of comments to help you:

ts = 'xyz abc mno def'
# separate at space to create a list
space = ' '
qs = ts.split(space)

# search for these items
search_list = ['abc', 'def', 'ghi']

# append this string to search item
s = 'zzz'

# now create a new list with processed search items
new_list = []
for q in qs:
    if q in search_list:
        # concatinate strings
        q += s
    new_list.append(q)

# join the list to form the modified string
new_ts = space.join(new_list)

print new_ts  # xyz abczzz mno defzzz
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.