Getting captured group in one line

前端 未结 9 1066
既然无缘
既然无缘 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:39

    You can do it as:

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

    Although it's not terribly efficient considering the fact that you run the regex twice.

    Or to run it only once as @Kevin suggested:

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

提交回复
热议问题