0

Using a regex expression, I am creating a function where certain criteria must be met (ex/ no white spaces allowed) and produces a tuple that is separated by a special character.

ex/ inputting a string of 'hello!world!hola' should produce a tuple of ('hello', 'world', 'hola').

I would like to raise a ValueError if the string does not meet my criteria. However, if the string does not meet my criteria, my code calls a AttributeError instead. Why is the function not properly calling the exception?

I tried to call a ValueError, but the function does not seem to catch my exception.

def produce_tupule (s):

    re_pair = re.compile(r'''^                        
                           ([a-zA-Z0-9._+-]+)
                           \!                            
                           ([a-zA-Z0-9._+-]+)
                           \!
                           ([a-zA-Z0-9._+-]+)
                           $              
                        ''',
                        re.VERBOSE)
    try:
        return (re_pair.match(s).groups())
    except ValueError as e:
        print(e)

I expect the output of produce_tupule('hello !world!hola') to result in the ValueError message since a whitespace exists in the string.

However, the error message points to the 'return:(re_pair.match(s).groups())' line and prints out an AttributeError: 'NoneType' object has no attribute 'groups'.

What is causing the function to not catch the exception and produce the AttributeError instead?

1 Answer 1

1

re.match returns None instead of raising a ValueError if the regular expression given fails to match your input. Your code then tries to access the .groups member of the None return value, which fails with an AttributeError.

If you want to raise a ValueError if the regular expression given fails to match, you have to do so explicitly by replacing your return (re_pair.match(s).groups()) line with code with explicit error checking:

match = re_pair.match(s)
if match is None:
    raise ValueError
return match.groups()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.