Reuse part of a Regex pattern

前端 未结 6 1547
北海茫月
北海茫月 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 14:44

    I was troubled with the same problem and wrote this snippet

    import nre
    my_regex=nre.from_string('''
    a=\d\w\w\d
    b={{a}},{{a}}
    c=?P{{a}}),(?P=id)
    ''')
    my_regex["b"].match("1aw2,5cx7")
    

    For lack of a more descriptive name, I named the partial regexes as a,b and c.

    Accessing them is as easy as {{a}}

提交回复
热议问题