Python regular expressions return true/false

Python regular expressions return true/false

Asked on January 11, 2019 in Regex.
Add Comment


  • 10 Answer(s)

    Python regular expressions return true or false:

    Use match objects are always true, and None is returned no match. Just test for true or false.

    if re.match(...):
    
    
    Answered on January 11, 2019.
    Add Comment

    Use bool method to check True or False:

    >>> bool(re.search("hi", "abcdefghijkl"))
    True
    >>> bool(re.search("hi", "abcdefgijkl"))
    False
    

    Using a condition for an if or while, use it directly without wrapping in bool().

     

    Answered on January 11, 2019.
    Add Comment

    Alternately use re.match() method:

    Using re.match() will return either None, which evaluates to False, or match object, which will always be True.

    Only if we want information about the part(s) that matched in regular expression to check out the contents of the match object.

    Answered on January 11, 2019.
    Add Comment

    If you really need True or False, just use bool

    >>> bool(re.search(“hi”, “abcdefghijkl”))
    True
    >>> bool(re.search(“hi”, “abcdefgijkl”))
    False
    As other answers have pointed out, if you are just using it as a condition for an if or while, you can use it directly without wrapping in bool()

    Answered on February 5, 2019.
    Add Comment
    <_sre.SRE_Match object at ...>
    Answered on May 20, 2019.
    Add Comment
    >>> bool(re.search("hi", "abcdefghijkl"))
    True
    >>> bool(re.search("hi", "abcdefgijkl"))
    False
    Answered on May 20, 2019.
    Add Comment
    import re
    
    if re.search("c", "abcdef"):
        print "hi"
    Answered on May 20, 2019.
    Add Comment

    Here is my method:

    import re
    p = re.complie(r'hi')
    print bool(p.match("abcdefghijkl"))
    Answered on May 20, 2019.
    Add Comment

    When you use match and search methods of module re, if there is a match, it has bool value of True and if there is no match, you get None that has a bool value of False.

    Match objects are always true, and None is returned if there is no match

    >>> bool(re.search("def", "abcdefgh"))
    True
    >>> bool(re.search("rest", "pqrstuv"))
    False
    Answered on May 20, 2019.
    Add Comment

    Boolean with re?

    Hey. Can you help please with the following. Using RE, I want to check a string, which is meant to be a passwords. True if it contains >= 10 chars, at least one lower letter, one capital letter and one number; else False. How would a code look like. Thanks.

    e.g. two cases:

    True = ‘bAse730onE4’

    False = ‘saaaa90’

    Answered on May 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.