2017-08-08 12 views
2

私は正規表現を作成してブローカデータ内のオプションシンボルを見つけようとしています。 Wikipediaあたり形式は:基礎となる株式やETFのPython Regex for Equity Optionが一致しません

  1. ルートシンボルは、フォーマットの6桁が
  2. オプションタイプをYYMMDD、
  3. 賞味期限6つの文字にスペースを埋め、P又はCのいずれかで、

    :用の8桁

に0との価格×1000、フロントパディングとして、入れたり

  • ストライク価格を呼び出すには、だから私は、この正規表現を作成しました
    option_regex = re.compile(r'''(
    (\w{1,6})   # beginning ticker, 1 to 6 word characters 
    (\s)?    # optional separator 
    (\d{6})    # 6 digits for yymmdd 
    ([cp])    # C or P for call or put 
    (\d{8})    # 8 digits for strike price 
    )''', re.VERBOSE | re.IGNORECASE) 
    

    しかし、私はそれをテストするとき、私はエラーを取得:

    import re 
    
    option_regex = re.compile(r'''(
    (\w{1,6})   # beginning ticker, 1 to 6 word characters 
    (\s)?    # optional separator 
    (\d{6})    # 6 digits for yymmdd 
    ([cp])    # C or P for call or put 
    (\d{8})    # 8 digits for strike price 
    )''', re.VERBOSE | re.IGNORECASE) 
    
    result = option_regex.search('AAPL 170818C00155000') 
    
    result.group() 
    Traceback (most recent call last): 
    
        File "<ipython-input-4-0273c989d990>", line 1, in <module> 
        result.group() 
    
    AttributeError: 'NoneType' object has no attribute 'group' 
    
  • +2

    わからないが、あなたの正規表現は、唯一のティッカーシンボルの後にスペースを可能にし、あなたの例の文字列を持っています二。 – brittenb

    +0

    ありがとう、それを逃した。 –

    答えて

    3

    python documentation on re.search()から:サブルーチンは何も見つからなかったので、

    Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

    あなたのコードは、この例外がスローされます。基本的には、None.group()を実行しようとしています。それを防御するために良いでしょう:それはあなたはそれがあると想定するものよりもより長い区切りを持っているので、

    if not result: 
        ... # Pattern didn't match the string 
        return 
    

    あなたのパターンは、あなたが入力した文字列と一致していません:それは、代わりに1の2つのスペースを持っています。あなたはルールに(「AT-少なくともワンス」)+を追加することによって、これを修正することができますタイプミスかの

    (\s+)?    # optional separator 
    
    関連する問題