2011-01-02 10 views
0

文字列内のキーワードをどのように一致させることができますか?キーワードに関連するオプションを探すにはどうすればよいですか?キーワードとキーワードのオプションのPython正規表現の文字列

これらは私が見つける必要があるキーワードおよびオプションは次のとおりです。

# 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 

私は知っているの私の正規表現ということ:ここで

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> 

は私が実験されているコードのスニペットです上記のコードは正しく動作しません。これは私の最初の適切なpythonスクリプトであり、私は自分の仕事を達成するために使用すべき方法が不明です。

ありがとうございました。

+0

あなたのregexソースには、多くのリテラル空白と改行が含まれています。それは何にもマッチしないことは間違いありません。 – 9000

+0

@ 9000このようなステートメントを作成する前にコードを実行することをお勧めします。私の正規表現は動作しますが、私が望む方法ではありません! Btwは正規表現の冗長なフォーマットhttp://diveintopython.org/regular_expressions/verbose.htmlを示すあなたのリンクです。 – joshu

答えて

1

あなたは、次の正規表現を試すことができ、それは特定の/より制限だと私はそれが動作するはずだと思う:

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

基本的にそれは<somevaliddata>続くタイプのいずれかを、一致しました。次に、2番目のマッチグループを取り出して分割するか、または/を押してすべての値を見つけます。申し訳ありませんが、それ以上のことをお手伝いすることはできません。私のPythonは盲目的にコード化するには余りにも錆びています。

+0

心配はいりません。あなたの正規表現は正しい軌道に乗っていて、2時間の "正規表現"の後に私が探していたものが得られます。再度、感謝します ;) – joshu

関連する問題