Home > database >  Is there a way to use the wildcard in a regex to replace with an index in a list?
Is there a way to use the wildcard in a regex to replace with an index in a list?

Time:07-02

So, say I have a string like this: Hello, [1]. And, I have a list like this: ["Joe", "Bob"] Now, I want to use a regex (or anything that will work) expression to replace the [?] (in this case [1]) with the corresponding index in the list (in this case, starting from index 0, the value is "Bob").

How do I do this?

The closest I've gotten has simply been re.sub("\[(?)\]", "\1", string)

But not only would this not do what I want, it also simply errors out anyway.

I have no clue how to do this, which is why I originally didn't put this attempt in the question.

CodePudding user response:

You can use re.sub with a callback argument.

import re

lst = ["Joe", "Bob"]
s = "Hello, [1]"
res = re.sub(r"\[(\d )]", lambda x: lst[int(x.group(1))], s)
print(res)  # "Hello, Bob"

CodePudding user response:

I'll give you a way to do it, a little less than optimal code but very easy to read and maintain (which I normally favor):

import re

def main():
    my_list = ["apple", "orange", "pear"]
    text = "Hello, [0] there [1] and [2]"
    
    my_dict = convert_to_dict(my_list)
    
    for key, value in my_dict.items():
        text = re.sub(f"\[{key}\]", value, text)
    
    print(text)
    
def convert_to_dict(my_list):
    my_dict = {}
    key_count = 0
    for item in my_list:
        my_dict[key_count] = item
        key_count  = 1
    return my_dict

if __name__ == "__main__":
    main()

I'm making a dictionary based upon the number of items in the list. Then the little tricky part is the regex, notice the f that allows me to use the variable key in the regex. You can read about that here: How to use a variable inside a regular expression? Good luck!

  • Related