2009-04-16 3 views
3

私はいくつかの電子メールアドレス、'[email protected]''[email protected]'を持っています。 PerlでPerlとPythonの正規表現の違いは?

、私は生の電子メールのTo:ラインを取ると、Pythonで

/\[email protected](tickets\.)?company\.com/i 

で上記アドレスのいずれかを見つけることができる、私は単純に同じ結果を期待し'\[email protected](tickets\.)?company\.com'として上記の正規表現を書きました。ただし、[email protected]はまったく見つからず、2番目のfindallは'tickets.'だけのリストを返します。明らかに'(tickets\.)?'が問題の領域ですが、PerlとPythonの間の正規表現ルールの違いは何ですか?

+0

いくつかのコードはどうですか? – Gumbo

答えて

7

ドキュメント:(tickets\.)以来

findall(pattern, string, flags=0) 
    Return a list of all non-overlapping matches in the string. 

    If one or more groups are present in the pattern, return a 
    list of groups; this will be a list of tuples if the pattern 
    has more than one group. 

    Empty matches are included in the result. 

全体ではなく、試合のグループ、findallリターンです。あなたがfindallによって返された各タプルの最初の要素を選択する必要がありますあなたは全体の試合をしたい場合は、マッチをパターン全体の周りにグループを置くおよび/または非グループ化を使用する、すなわち

r'(\[email protected](tickets\.)?company\.com)' 
r'\[email protected](?:tickets\.)?company\.com' 

注意最初のケース。

+0

さて、興味深いことに、明らかではない*。 – Axeman

2

2つの問題私に飛び出す:

  1. あなたがそうしてみてくださいあなたが「.

をエスケープする必要がある「\

  • を脱出することを避けるために、生の文字列を使用する必要があります:

    r'\[email protected](tickets\.)?company\.com' 
    

    EDIT

    出力例:

    >>> import re 
    >>> exp = re.compile(r'\[email protected](tickets\.)?company\.com') 
    >>> bool(exp.match("[email protected]")) 
    True 
    >>> bool(exp.match("[email protected]")) 
    True 
    
  • +0

    私はこの提案を2番目にします。 –

    +0

    #2私はstackoverflowでnewbされているだけです。最初の投稿を修正しました。 ;) –

    4

    私は問題が抽出された値のあなたの期待していると思います。あなたの現在のPythonコードでこれを使用してみてください:re.findallため

    '(\[email protected](?:tickets\.)?company\.com)' 
    
    1

    正規表現には違いはありませんが、探しているものに違いがあります。あなたの正規表現は両方の正規表現に存在する場合、"tickets."だけをキャプチャしています。あなたはおそらくこのような何かをしたいでしょう

    #!/usr/bin/python 
    
    import re 
    
    regex = re.compile("(\[email protected](?:tickets\.)?company\.com)"); 
    
    a = [ 
        "[email protected]", 
        "[email protected]", 
        "[email protected]", 
        "[email protected]" 
    ]; 
    
    for string in a: 
        print regex.findall(string)