Reuse part of a Regex pattern

前端 未结 6 1551
北海茫月
北海茫月 2020-11-28 14:40

Consider this (very simplified) example string:

1aw2,5cx7

As you can see, it is two digit/letter/letter/digit values separated

6条回答
  •  隐瞒了意图╮
    2020-11-28 15:04

    Since you're already using re, why not use string processing to manage the pattern repetition as well:

    pattern = "P,P".replace("P",r"\d\w\w\d")
    
    re.match(pattern, "1aw2,5cx7")
    

    OR

    P = r"\d\w\w\d"
    
    re.match(f"{P},{P}", "1aw2,5cx7")
    

提交回复
热议问题