๊ฐœ์š”

sub ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š” ๋ถ€๋ถ„์„ ๋‹ค๋ฅธ ๋ฌธ์ž๋กœ ์‰ฝ๊ฒŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.

>>> p = re.compile('(blue|white|red)')
>>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour shoes'

์ฒซ๋ฒˆ์งธ ๋ณ€์ˆ˜๋Š” ๋ฐ”๊ฟ€ ๋ฌธ์ž์—ด, ๋‘๋ฒˆ์งธ ๋ณ€์ˆ˜๋Š” ๋Œ€์ƒ ๋ฌธ์ž์—ด์ด๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ๋งŒ์•ฝ ํ•œ๋ฒˆ๋งŒ ๋ฐ”๊พธ๊ณ  ์‹ถ๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ? ์„ธ๋ฒˆ์งธ ๋ณ€์ˆ˜๋กœ count๋ฅผ ๋„˜๊ธฐ๋ฉด ๋œ๋‹ค.

>>> p.sub('colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'

์ฒ˜์Œ ์ผ์น˜ํ•œ ๋ถ€๋ถ„๋งŒ ๋ณ€๊ฒฝ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

subn ์—ญ์‹œ sub์™€ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ํ•˜์ง€๋งŒ ๋ฐ˜ํ™˜ ๊ฒฐ๊ณผ๋ฅผ ํŠœํ”Œ๋กœ ๋Œ๋ ค์ค€๋‹ค๋Š” ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค. ๋Œ๋ ค์ค€ ํŠœํ”Œ์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋Š” ๋ณ€๊ฒฝ๋œ ๋ฌธ์ž์—ด์ด๊ณ , ๋‘ ๋ฒˆ์งธ ์š”์†Œ๋Š” ๋ฐ”๊พธ๊ธฐ๊ฐ€ ๋ฐœ์ƒํ•œ ํšŸ์ˆ˜์ด๋‹ค.

>>> p = re.compile('(blue|white|red)')
>>> p.subn( 'colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)

์ฐธ์กฐ ๊ตฌ๋ฌธ ์‚ฌ์šฉํ•˜๊ธฐ

์ฐธ์กฐ ๊ตฌ๋ฌธ์€ ๊ทธ๋ฃจํ•‘์—์„œ ๊ฒ€์ƒ‰๋œ ๊ฒƒ์— ๋Œ€ํ•ด ๋„ค์ด๋ฐ์„ ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๋งํ–ˆ๋‹ค. ์ด๋Ÿฐ ๊ธฐ๋Šฅ์„ sub์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ํฌ๋งท์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋‹ค.

>>> p = re.compile(r"(?P<name>\w+)\s+(?P<phone>(\d+)[-]\d+[-]\d+)")
>>> print(p.sub("\g<phone> \g<name>", "park 010-1234-1234"))
010-1234-1234 park

์œ„ ์˜ˆ๋Š” ์ด๋ฆ„ + ์ „ํ™”๋ฒˆํ˜ธ์˜ ๋ฌธ์ž์—ด์„ ์ „ํ™”๋ฒˆํ˜ธ + ์ด๋ฆ„์œผ๋กœ ๋ฐ”๊พธ๋Š” ์˜ˆ์ด๋‹ค. sub์˜ ๋ฐ”๊ฟ€ ๋ฌธ์ž์—ด ๋ถ€๋ถ„์— \g<๊ทธ๋ฃน์ด๋ฆ„>์„ ์‚ฌ์šฉํ•˜๋ฉด ์ •๊ทœ์‹์˜ ๊ทธ๋ฃน ์ด๋ฆ„์„ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ทธ๋ฃน ์ด๋ฆ„ ๋Œ€์‹  ์ฐธ์กฐ ๋ฒˆํ˜ธ๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋งˆ์ฐฌ๊ฐ€์ง€ ๊ฒฐ๊ณผ๋ฅผ ๋Œ๋ ค์ค€๋‹ค.

>>> p = re.compile(r"(?P<name>\w+)\s+(?P<phone>(\d+)[-]\d+[-]\d+)")
>>> print(p.sub("\g<2> \g<1>", "park 010-1234-1234"))
010-1234-1234 park

ํ•จ์ˆ˜๋ฅผ ๋„ฃ์–ด ์‚ฌ์šฉํ•˜๊ธฐ

>>> def hexrepl(match):
...     value = int(match.group())
...     return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'

hexrepl ํ•จ์ˆ˜๋Š” match ๊ฐ์ฒด(์œ„์—์„œ ์ˆซ์ž์— ๋งค์น˜๋˜๋Š”)๋ฅผ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์•„ 16์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋Œ๋ ค์ฃผ๋Š” ํ•จ์ˆ˜์ด๋‹ค. sub์˜ ์ฒซ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ํ•ด๋‹น ํ•จ์ˆ˜์˜ ์ฒซ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜์—๋Š” ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋œ match ๊ฐ์ฒด๊ฐ€ ์ž…๋ ฅ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋งค์น˜๋˜๋Š” ๋ฌธ์ž์—ด์€ ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜ ๊ฐ’์œผ๋กœ ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค.

Reference