Re.match() returns always none

前端 未结 2 657
清歌不尽
清歌不尽 2020-11-29 12:04

I feel kind of stupid but it does not work:

import re

a = \" ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523         


        
相关标签:
2条回答
  • 2020-11-29 12:55

    re.match is implicitly anchored to the start of the string. If you want to search a string for a substring that can be anywhere within it, then you need to use re.search:

    import re
    
    a = " ebrj wjrbw erjwek wekjb rjERJK ABB RAEJKE BWE RWEJBEWJ B KREWBJ BWERBJ32J3B23B J BJ235JK BJJ523 2"
    
    print re.search(ur'(wekjb|ABB)',a).group()
    if re.search(ur'(wekjb|ABB)',a):
        print 'success'
    

    Output:

    wekjb
    success
    

    Also, Python Regexes do not need to have a / at the start and end.

    Lastly, I added .group() to the end of the print line because I think this is what you want. Otherwise, you'd get something like <_sre.SRE_Match object at 0x01812220>, which isn't too useful.

    0 讨论(0)
  • 2020-11-29 12:58

    It's because of that match method returns None if it couldn't find expected pattern, if it find the pattern it would return an object with type of _sre.SRE_match .

    So, if you want Boolean (True or False) result from match you must check the result is None or not!

    You could examine texts is matched or not somehow like this:

    string_to_evaluate = "Your text that needs to be examined"
    expected_pattern = "pattern"
    
    if re.match(expected_pattern, string_to_evaluate) is not None:
        print("The text is as you expected!")
    else:
        print("The text is not as you expected!")
    
    0 讨论(0)
提交回复
热议问题