Skip to content

Instantly share code, notes, and snippets.

@idank
Created August 29, 2013 19:33
Show Gist options
  • Save idank/6382427 to your computer and use it in GitHub Desktop.
Save idank/6382427 to your computer and use it in GitHub Desktop.
opt_regex = re.compile(r'''
(?P<opt>--?(?:\?|\#|(?:\w+-)*\w+)) # option starts with - or -- and can have - in the middle but not at the end, also allow '-?'
(?:
(?:\s*(=)?\s*) # -a=
(?P<argoptional>[<\[])? # -a=< or -a=[
(?:\s*(=)?\s*) # or maybe -a<=
(?P<arg>
(?(argoptional) # if we think we have an arg (we saw [ or <)
[^\]>]+ # either read everything until the closing ] or >
|
(?(2)
[-a-zA-Z]+ # or if we didn't see [ or < but just saw =, read all letters, e.g. -a=abc
|
[A-Z]+ # but if we didn't have =, only allow uppercase letters, e.g. -a FOO
)
)
)
(?(argoptional)(?P<argoptionalc>[\]>])) # read closing ] or > if we have an arg
)? # the whole arg thing is optional
(?P<ending>,\s*|\s+|\Z|/|\|)''', re.X) # read any trailing whitespace or the end of the string
opt2_regex = re.compile(r'''
(?P<opt>\w+) # an option that doesn't start with any of the usual characters, e.g. options from 'dd' like bs=BYTES
(?:
(?:\s*=\s*) # an optional arg, e.g. bs=BYTES
(?P<arg>\w+)
)
(?:,\s*|\s+|\Z)''', re.X) # end with , or whitespace or the end of the string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment