开发者

Python regex string for keyword and keyword options

How do I match a keyword in a string and if found look for options related to the keyword?

These are the keywords and options that I need to find:

Standard

Snow <start date> <end date> Example: <24/12/2010> <9/1/2011>

Rain <all day> or <start time> <end time> Example: <8:30> <10:45> or <10:30> <13:00>

Wind <all day> or <start time> <end time> Example: <8:30> <10:45> or <10:30> <13:00>

Here is a snippet of code that I have been experimenting with:

# This is the string that should match one of those shown above.
# Btw the string is the result of user input from a different process.
mystring = 'Rain <8:30> <10:45>'

# Validate string
if mystring == '':
     print 'Error: Missing information'
     sys.exit(1)

# Look for keywords in mystring    
Regex = re.compile(r'''
    ^(\w+)
    \D+
    (\d)
    \D+
    (\d{2})
    ''', re.VERBOSE)

match = Regex.search(mystring)

# print matching information for debugging
print 'match: ' + str(match)
print 'all groups: ' + match.group(0)
print 'group 1: ' + match.group(1)
print 'group 2: ' + match.group(2)
print 'group 3: ' + match.group(3)

# if match.group(1) equates to one of the keywords
# (e.g. Standard, Snow, Rain or Wind)
# check that the necessary options are in mystring
if match.group(1) == 'Standard':
     print 'Found Standard'
     # execute external script
elif match.group(1) == 'Snow':
     print 'Found Snow'
     # check for options (e.g. <start date> <end date>
     # if options are missing or wrong sys.exit(1)
     # if options are correct execute external script
elif match.group(1) == 'Rain':
     print 'Found Rain'
     # check for options (e.g. <all day> or <start time> <end time>
     # if options are missing or wrong sys.exit(1)
     # if options are correct execute external script
elif match.group(1) == 'Wind':
     print 'Found Wind'
     # check for options (e.g. <all day> or <start time> <end time>
     # if options are missing or wrong sys.exit(1)
     # if options are correct execute external script

I know that my regex in the code above does not work proper开发者_StackOverflow中文版ly. This is my first proper python script and I'm unsure of the method(s) I should use to accomplish my task.

Thanks.


You can try the following regex, it's more restrictive/specific and I think it should work:

Regex = re.compile(r'''
^(Rain|Snow|Wind|Standard) <(\d+:\d+|\d+/\d+/\d+)>
''', re.VERBOSE)

Essentially it matches one of the types, followed by <somevaliddata>. Then you can take the second match group and split it on : or / to find all your values. Sorry I can't help you much more than that, my python is too rusty to code blindly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜