Python: how to substitute and know whether it matched

前端 未结 3 459
温柔的废话
温柔的废话 2021-01-05 00:53

I know that re.sub(pattern, repl,text) can substitute when pattern matches, and then return the substitute.

My code is:

text = re.sub(p         


        
3条回答
  •  囚心锁ツ
    2021-01-05 01:25

    Use re.subn

    Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

    and then check the number of replacements that were made. For example:

    text2, numReplacements = re.subn(pattern, repl, text1)
    if numReplacements:
        # did match
    else:
        # did not match
    

提交回复
热议问题