Search code examples
pythonregexbackreferencecapturing-groupcapture-group

Python : Convert Integers into a Count (i.e. 3 --> 1,2,3)


This might be more information than necessary to explain my question, but I am trying to combine 2 scripts (I wrote for other uses) together to do the following.

TargetString (input_file) 4FOO 2BAR

Result (output_file) 1FOO 2FOO 3FOO 4FOO 1BAR 2BAR

My first script finds the pattern and copies to file_2

pattern = "\d[A-Za-z]{3}"
matches = re.findall(pattern, input_file.read())
f1.write('\n'.join(matches))

My second script opens the output_file and, using re.sub, replaces and alters the target string(s) using capturing groups and back-references. But I am stuck here on how to turn i.e. 3 into 1 2 3.

Any ideas?


Solution

  • This simple example doesn't need to use regular expression, but if you want to use re anyway, here's example (note: you have minor error in your pattern, should be A-Z, not A-A):

    text_input = '4FOO 2BAR'
    
    import re
    
    matches = re.findall(r"(\d)([A-Za-z]{3})", text_input)
    
    for (count, what) in matches:
        for i in range(1, int(count)+1):
            print(f'{i}{what}', end=' ')
    
    print()
    

    Prints:

    1FOO 2FOO 3FOO 4FOO 1BAR 2BAR 
    

    Note: If you want to support multiple digits, you can use (\d+) - note the + sign.