用于关键字和关键字选项的Python正则表达式字符串

时间:2011-01-02 13:19:31

标签: python regex string

如何匹配字符串中的关键字,如果找到,则查找与关键字相关的选项?

这些是我需要找到的关键字和选项:

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>

以下是我一直在尝试的代码片段:

# 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

我知道上面代码中的正则表达式无法正常工作。这是我的第一个正确的python脚本,我不确定我应该用来完成任务的方法。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下正则表达式,它更具限制性/特定性,我认为它应该有效:

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

基本上它匹配其中一种类型,然后是&lt; somevaliddata&gt;。然后,您可以将第二个匹配组拆分为:或/以查找所有值。对不起,我无法帮助你,我的python太生锈了,无法盲目编码。