본문 바로가기
파이썬

파이썬 re.sub 그룹 : \ number 뒤의 숫자

by º기록 2020. 10. 2.
반응형

foobar foo123bar 로 어떻게 바꿀 수 있습니까?

작동하지 않습니다.

>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'

이것은 작동합니다 :

>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'

\ number 와 같은 것을 가질 때 일반적인 문제라고 생각합니다. 누구든지 이것을 처리하는 방법에 대한 힌트를 줄 수 있습니까?

 

해결 방법

 

정답은:

re.sub(r'(foo)', r'\g<1>123', 'foobar')

문서에서 관련 발췌 :

문자 이스케이프 및 backreferences as described above, \g will use the substring matched by the group named name, as defined by the (?P...) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the 레.

 

참조 페이지 https://stackoverflow.com/questions/5984633

 

 

반응형

댓글