Python正则表达式用于关键词和关键词选项

0 投票
1 回答
957 浏览
提问于 2025-04-16 09:18

我想知道怎么在一个字符串中找到一个关键词,如果找到了,就去找和这个关键词相关的选项。

以下是我需要找到的关键词和选项:

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 个回答

1

你可以试试下面这个正则表达式,它更严格一些,我觉得应该能用:

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

这个表达式基本上是匹配某种类型,后面跟着<一些有效的数据>。然后你可以取第二个匹配的部分,用 : 或 / 来分割,找到你所有的值。抱歉我帮不了你更多,我的Python水平有点生疏,不能随便写代码。

撰写回答