πŸ’‘ μ •κ·œν‘œν˜„μ‹_파이썬 TIL#34

may_soouuΒ·2020λ…„ 8μ›” 16일
0

νŒŒμ΄μ¬μ— μ •κ·œν‘œν˜„μ‹ μ μš©ν•˜κΈ°

πŸ‘†πŸ» νŒŒμ΄μ¬μ—μ„œ μ •κ·œν‘œν˜„μ‹μ„ ν™œμš©ν•˜λ €λ©΄?

  • νŒŒμ΄μ¬μ—μ„œ μ •κ·œν‘œν˜„μ‹μ„ ν™œμš©ν•˜λ €λ©΄ μš°μ„ , re λͺ¨λ“ˆμ„ import ν•΄μ•Όν•œλ‹€.
    그리고 re.compile을 μ‚¬μš©ν•˜μ—¬ μ •κ·œν‘œν˜„μ‹μ„ μ»΄νŒŒμΌν•œλ‹€.
import re
p = re.compile('ab*')

컴파일된 νŒ¨ν„΄ 객체의 4가지 λ©”μ†Œλ“œ

  • match() : λ¬Έμžμ—΄μ˜ μ²˜μŒλΆ€ν„° μ •κ·œμ‹κ³Ό λ§€μΉ˜λ˜λŠ”μ§€ 쑰사
  • search() : λ¬Έμžμ—΄μ˜ 전체λ₯Ό κ²€μƒ‰ν•˜μ—¬ μ •κ·œμ‹κ³Ό λ§€μΉ˜λ˜λŠ”μ§€ 쑰사
  • findall() : μ •κ·œμ‹κ³Ό λ§€μΉ˜λ˜λŠ” λͺ¨λ“  λ¬Έμžμ—΄μ„ 리슀트둜 돌렀쀌
  • finditer() : μ •κ·œμ‹κ³Ό λ§€μΉ˜λ˜λŠ” λͺ¨λ“  λ¬Έμžμ—΄μ„ 반볡 κ°€λŠ₯ν•œ 객체둜 돌렀쀌
    match와 searchλŠ” μ •κ·œμ‹κ³Ό 맀치될 λ•ŒλŠ” 객체λ₯Ό 돌렀주고, λ§€μΉ˜λ˜μ§€ μ•Šμ„ λ•ŒλŠ” None을 λŒλ €μ€€λ‹€!
p = re.compile(μ •κ·œν‘œν˜„μ‹)
m = p.match( 'string goes here' )
if m:
    print('Match found: ', m.group())
else:
    print('No match')
    
---------------------------
match μ˜ˆμ‹œ.
import re

p = re.compile('[a-z]')
m = p.match('alpha123')
if m:
    print('Match found: ', m.group())
else:
    print('No match')  #result : a
    
import re

p = re.compile('alp')
m = p.match('p alp')
if m:
    print('Match found: ', m.group())
else:
    print('No match')  #result: no match
-----------------------------
search μ˜ˆμ‹œ
import re

p = re.compile('alp')
m = p.search('p alp')
if m:
    print('Match found: ', m.group())
else:
    print('No match')  #result : alp
    
-----------------------------
findall μ˜ˆμ‹œ

import re

p = re.compile('[a-i]')
result = p.findall("life is too short")
print(result)   #result : ['i', 'f', 'e', 'i', 'h'] 리슀트둜 돌렀쀌

------------------------------
finditer μ˜ˆμ‹œ

import re

p = re.compile('[a-i]')
result = p.finditer("life is too short")
print(result)
for r in result : print(r)

#resultπŸ‘‡πŸ» : 반볡 κ°€λŠ₯ν•œ 객체둜 돌렀쀌
<callable_iterator object at 0x000001BC87165F48>
<re.Match object; span=(1, 2), match='i'>
<re.Match object; span=(2, 3), match='f'>
<re.Match object; span=(3, 4), match='e'>
<re.Match object; span=(5, 6), match='i'>
<re.Match object; span=(13, 14), match='h'>

match객체의 λ©”μ„œλ“œ

methodλͺ©μ 
group()맀치된 λ¬Έμžμ—΄μ„ λŒλ €μ€€λ‹€
start()맀치된 λ¬Έμžμ—΄μ˜ μ‹œμž‘μœ„μΉ˜λ₯Ό λŒλ €μ€€λ‹€
end()맀치된 λ¬Έμžμ—΄μ˜ λμœ„μΉ˜λ₯Ό λŒλ €μ€€λ‹€
span()맀치된 λ¬Έμžμ—΄μ˜ (μ‹œμž‘,끝)에 ν•΄λ‹Ήν•˜λŠ” νŠœν”Œμ„ λŒλ €μ€€λ‹€
μ˜ˆμ‹œ
>>> m = p.match("python")
>>> m.group()
'python'
>>> m.start()
0
>>> m.end()
6
>>> m.span()
(0, 6)

* strat의 값은 항상 0일것! μ™œ?! matchλ©”μ„œλ“œλŠ” 항상 λ¬Έμžμ—΄μ˜ μ‹œμž‘λΆ€ν„° μ‘°μ‚¬ν•˜κΈ° λ•Œλ¬Έ!

μΆ•μ•½ν˜•νƒœ
p = re.compile('[a-z]+')
m = p.match("python")
λ₯Ό μΆ•μ•½ν•˜λ©΄
m = re.match('[a-z]+', "python")

  • ν•œλ²ˆ λ§Œλ“  νŒ¨ν„΄ 객체λ₯Ό μ—¬λŸ¬λ²ˆ μ‚¬μš©ν•΄μ•Όν•  λ•ŒλŠ” re.compile 방법을 μ“°μž!
profile
back-end 개발자

0개의 λŒ“κΈ€