简体   繁体   中英

Python argparse regex expression

Is it possible to use a regex expression for parsing an argument? For example, I want to accept an argument if only it is a 32 length hex (ie matches /[a-f0-9A-F]{32}/ )

I tried

p.add_argument('hex', type=str, nargs="[a-f0-9A-F]{32}")

without success

The type keyword argument can take any callable that accepts a single string argument and returns the converted value. If the callable raises argparse.ArgumentTypeError , TypeError , or ValueError , the exception is caught and a nicely formatted error message is displayed.

import argparse
import re 
from uuid import uuid4

def my_regex_type(arg_value, pat=re.compile(r"^[a-f0-9A-F]{32}$")):
    if not pat.match(arg_value):
        raise argparse.ArgumentTypeError
    return arg_value

parser = argparse.ArgumentParser()
parser.add_argument('hex', type=my_regex_type)

args = parser.parse_args([uuid4().hex])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM