简体   繁体   中英

Regex for matching optional parameters as groups in string

I am trying to read a batch script containing an input string of a command and optional parameters like

input = 'command -a field1 -b field2 -c field3'

The option parameters are set by a user in a file and I am obtaining the string by reading the file. If the option is included I would need to extract the field.

I currently have my regex as:

expr = '^(?P<exec>[^\s]+) -m (?P<mode>[^\s]+) -d (?P<machine>[^\s]+) -p (?P<port>[^\s]+)'
m = re.match(expr, input)

When the user includes all the options in the same order, the regex matches the string and the groups are captured. Here is a sample output.

{   'exec': 'custom-script',
    'mode': 'debug',
    'machine': 'desk-123',
    'port': '7905'   }

However, if any option is not included, or if they are in different orders, the regex fails. How do I modify my regex to perform in these two cases?

In Python you can use the built in optparse or argparse modules to do this for you so you don't have to fidget with hardcore regular expressions which will fail eventually:-)

parsing command line options with regular expressions in python is very fragile - argparse will let you handle all of the arguments you want, both optional and positional, and provides abundant faculties for manipulating them. It even automatically builds a -h option for you!

For example, in your case you said you have the input supplied to you, so you could do the following:

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-m','--mode', help='The mode to run in')
parser.add_argument('-d','--machine', help='The machine of interest')
parser.add_argument('-p','--port', help='The port of interest')
args = parser.parse_args(input.split())

The output from this, args , will have the different fields as attributes, ie, args.mode , args.machine , args.port

Thanks to Nate, I used optparse instead of regexes and used the following code:

parser = optparse.OptionParser(description='Process some integers.')
parser.add_option('-m','--mode', help='The mode to run in')
parser.add_option('-d','--machine', help='The machine of interest')
parser.add_option('-p','--port', help='The port of interest')
(args, others) = parser.parse_args(input.split())

Now, I can access the values by args.mode, args.machine, etc.

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