1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Regex: validating repeated cmd-line options

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

  1. Stack

    Stack Membro Participativo

    I am using Python re to validate a command line options.

    This is the portion that is giving me hard times: a repeated, or non-mandatory, -c snake_case=1-like option.

    I tried to fake the regex engine by adding a hard-coded extra option, at the cost of an further post-processing cleaning operation, with no success.

    Then I also tried to truncate the length of each option, keeping the regex invariant, and it works... but, of course, I cannot use it in my project.

    How should I build a reliable regex to handle the problem?

    import re


    # regex
    r = r'(?:-c\s[a-z_]+=1\s?)*'

    # real case: failure
    cmd = '-c tessedit_write_images=1 -c wordrec_display_segmentations=1'
    print(re.search(r, cmd))
    #<re.Match object; span=(0, 27), match='-c tessedit_write_images=1 '>


    # fake case: truncated length of options: correct result
    cmd = '-c dit_write_images=1 -c wrec_display_segm=1'
    print(re.search(r, cmd))
    #<re.Match object; span=(0, 44), match='-c dit_write_images=1 -c wrec_display_segm=1'>

    Continue reading...

Compartilhe esta Página