2

I am currently trying to use re.match function from python. I then have an if statment where if re.match returns anything(indicating that the regex is contained in the string) then it will return what the original string was.Otherwise if it fails I would want to return the word 'failed'.

How would I be able to do this?

Short form: How can an if statement accept any value that isn't a non return.

  • Are you looking for `if re.match(...) is None`? `re.match` returns None if the regex doesn't match. – BrenBarn Nov 23 '12 at 21:12
  • This doesn't sound like good design. Your return value has two different roles. I would return a boolean that marks success or failure, and another string for extra data. – Ilya Kogan Nov 23 '12 at 21:12
  • I wasn't aware is none existed, thanks. With regards to the design its not exactly as how I described but I tried to simplify my question so I could get a quick answer. Thank you. –  Nov 23 '12 at 21:15

2 Answers2

3
def func(s):
    pattern = "somepattern"
    return s if re.match(pattern, s) else 'failed'

Also, returning "failed" sounds like a bad idea. What if the input is "failed"? Consider using something like None.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • both example are equivalent regardless whether the match is empty string or not because re.match() returns either None or Match object (not string). – jfs Nov 23 '12 at 22:09
1

You can use truthiness:

if re.match(r'your_regex', your_string):
    return your_string
else:
    return 'failed'

If re.match returns anything that isn't false-like ([], {}, (), 0, '' None, False, etc.), then it is evaluated as True.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • I wasn't aware you could do that. I will go test that out now thank you. –  Nov 23 '12 at 21:14
  • Note: in general these are also false values: ["instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False."](http://stackoverflow.com/questions/1452489/evaluation-of-boolean-expressions-in-python). Though it doesn't matter in this case: re.match returns either None or a Match object that is always true. – jfs Nov 23 '12 at 22:18
  • @J.F.Sebastian: Thanks for the info. I didn't know about `__nonzero__` and `__bool__` for Python 3. – Blender Nov 23 '12 at 22:19