2017-08-15 8 views
-2

サブストリングの代わりにチャンクでキー値ペアリングチャンクを照合しようとしていますので、一致するようにしています[email protected]私は[email protected](?!|\S)を使用しています私は部分文字列のマッチにヒットしないようにします。そして、https://regex101.com/r/ehuXFY/1によればそれは動作します。しかし、ここで私のユニットテストマッチは、文字列の末尾にある場合は、動作していないようです:あなたがre.searchを使用する必要があるときは、re.matchを使用しているターゲットが行末にある場合、Pythonの正規表現が一致しない

import unittest 
import re 


class MyRegexFuTestCases(unittest.TestCase): 
    def test_something(self): 
     lines = [ 
      '[email protected]\talias= <[email protected]>\[email protected]\trip=8.8.8.8\tdate=1486528190\tsubject= Test Subject\[email protected]\treport=leoisafatcat\tattach_3=New List.xls'] 
     whitelisted_pairs = ['attach_3=New List.xls'] 
     lines = filter(lambda line: any(
      map(lambda pair: not re.match(r'%s(?!\S)' % pair, line), 
       whitelisted_pairs)), lines) 
     self.assertEqual(len(lines), 0) 

    def test_another_case(self): 
     lines = [ 
      '[email protected]\talias= <[email protected]>\[email protected]\trip=8.8.8.8\tdate=1486528190\tsubject= Test Subject\[email protected]\treport=leoisafatcat\tattach_3=New List.xls'] 
     whitelisted_pairs = ['[email protected]'] 
     lines = filter(lambda line: any(
      map(lambda pair: not re.match(r'%s(?!\S)' % pair, line), 
       whitelisted_pairs)), lines) 
     self.assertEqual(len(lines), 0) 

    def test_no_match(self): 
     lines = [ 
      '[email protected]\talias= <[email protected]>\[email protected]\trip=8.8.8.8\tdate=1486528190\tsubject= Test Subject\[email protected]\treport=leoisafatcat\tattach_3=New List.xls'] 
     whitelisted_pairs = ['[email protected]'] 
     lines = filter(lambda line: any(
      map(lambda pair: not re.match(r'%s(?!\S)' % pair, line), 
       whitelisted_pairs)), lines) 
     self.assertEqual(len(lines), 1) 

if __name__ == '__main__': 
    unittest.main() 



..F 
====================================================================== 
FAIL: test_something (__main__.MyRegexFuTestCases) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/Users/stupidfatcat/PycharmProjects/adhoc/so_help.py", line 13, in test_something 
    self.assertEqual(len(lines), 0) 
AssertionError: 1 != 0 

---------------------------------------------------------------------- 
Ran 3 tests in 0.001s 

FAILED (failures=1) 
+0

違いを説明できますか?なぜ 'from = test_email @ email.co'で' .com'でないのですか? –

+0

@ jean-francoisFabreメールがemail.comであるため、email.coで一致させたくありません。私。私は部分文字列のマッチを望んでいません。 –

+1

なぜこの複合体 '(?!\ S)'の代わりに単語境界に '\ b'を使用しないのですか? –

答えて

2

match行の先頭に正規表現を一致させようとします。したがって、最後の2つのテストケースが一致するのは、ラインの最初から開始されるためです。一方、期待どおりの動作をしているのに対し、

searchがあります。これは、ラインの任意の部分に対して正規表現にマッチします。

+1

're.match'は"行全体に対して "正規表現をマッチさせようとしません。それは文字列の先頭にのみ一致します。 '.matches()'が完全な文字列の一致を必要とするのはJavaではありません。 –

+0

ああ、そうです。私は何かを学んでいる:-)決してJavaで正規表現を行った。私は私の答えを編集しました。 – pchaigno

+0

're.match'は* lines *を認識しません。*文字列全体*の先頭で常に一致するものを探します。 're.MULTILINE'フラグがあっても。 –

関連する問題