Getting captured group in one line

前端 未结 9 1069
既然无缘
既然无缘 2020-12-16 18:23

There is a known \"pattern\" to get the captured group value or an empty string if no match:

match = re.search(\'regex\', \'text\')
if match:
    value = mat         


        
9条回答
  •  青春惊慌失措
    2020-12-16 18:41

    It's possible to refer to the result of a function call twice in a single one-liner: create a lambda expression and call the function in the arguments.

    value = (lambda match: match.group(1) if match else '')(re.search(regex,text))
    

    However, I don't consider this especially readable. Code responsibly - if you're going to write tricky code, leave a descriptive comment!

提交回复
热议问题