[Python] How to include a variable in a Regex mask with Python [duplicate]

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have a file where I am searching for a certain section of a string (the initial 'C' and either 111 or 112 in this case) and then extracting some bytes further along the string. I have been using a regex re.compile mask to do this and it works fine. Unfortunately the 'standardised' identifier I am searching for turns out not to be standardised. While I am running it as code, then I can just change the coded mask manually, but the plan is to convert to an .exe so others can use it. I therefore need to be able to have user variable input from a GUI.
    How do I include a variable in a regex mask?

    The data I am searching for:

    C001PA021 111 1001605532.89N0033634.67E 533050.66754836.8 0.01201505464
    C001PA021 112 1001605532.72N0033633.89E 533038.96754831.2 0.01201505464


    And the regex I am currently using:

    CDP111 = re.compile(r"^C\w*(?:-\d+)?(?:-\d+)?\W*111\b")
    CDP112 = re.compile(r"^C\w*(?:-\d+)?(?:-\d+)?\W*112\b")


    The part that changes is the 111 or 112 at the end of my mask in these examples. It will be the constant in each file I read, and always be a three digit number, but could be anything from 111 to 999. The next file may have different three digit codes. The user will be able to enter these in the GUI.

    What is the correct syntax for:

    my_variable_1 = 123 # Get from Gui
    my_variable_2 = 321 # Get from Gui
    CDP111 = re.compile(r"^C\w*(?:-\d+)?(?:-\d+)?\W*my_variable_1\b")
    CDP112 = re.compile(r"^C\w*(?:-\d+)?(?:-\d+)?\W*my_variable_2\b")


    I created the original regex using this website. There are some other data examples here to experiment with - various endings e.g. 113, 122, 124 . https://regex101.com/r/yfHf2W/1 I have looked through a number of the previous answers to similar questions on here and can't find one that matches closely enough. Several are similar, but Java, and some go in other directions. I have also looked at the Regex.wiki. I really struggle with the / and parenthesis.

    Continue reading...

Compartilhe esta Página