Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Function to dictate the replacements in re.sub method (Python)

Trying to use regex to perform substitutions on a string.

re.sub(regex, repl_func, content)

The problem is that I do not understand how the replacement will occur via the repl_func when I need the substitution to be dependent on the matching object from that regex; i.e. I will use that matched object as a dictionary key to get the matching value with which that particular object needs to be replaced.

    for mobj in re.finditer(regex, content):
        t = mobj.lastgroup
        v = match_obj.group(t)

        if t == 'NAME':
            ...
        elif t == '
':
            ...

I have tried to iterate all the matching objects, as seen above, but cannot figure out how to apply the re.sub. If I understand correctly, the repl_function in my first code segment needs to somehow know which is the matched object from that regex.

Any ideas, especially using code will be much appreciated cause I am only just now starting with Python.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The re.sub() function passes the matched object to repl_function as an argument and replaces the returned result from that function with the matched string. If you want to replace the matched object with a particular string in a dictionary you can simply use a function to handle that:

def repl_func(matched_obj):
    my_dict = {'NAME':'rep1', '
':'rep2'}
    try:
        match = matched_obj.group(0)
    except AttributeError:
        matched = ''
        # Or raise an exception
    else:
        return my_dict.get(match, '')

re.sub(regex, repl_func, content)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...