In [1]:
import re
In [2]:
text = 'Learning Python 101: 2016-07-14'
In [3]:
p = re.compile('\d')
In [4]:
s = p.search(text)
In [5]:
if s is not None:
print(s.group(0))
In [6]:
s = re.search('\d', text)
In [7]:
if s is not None:
print(s.group(0))
timeit 매직 커맨드를 이용한 속도 비교
In [8]:
%timeit -n 100 p.search(text)
In [9]:
%timeit -n 100 re.search('\d', text)
In [10]:
m = re.match('\d', text)
In [11]:
m is None
Out[11]:
In [12]:
m = re.match('.*\d', text)
In [13]:
if m is not None:
print(m.group())
In [14]:
m = re.match('.*?\d', text)
In [15]:
if m is not None:
print(m.group())
매칭 문자열 그룹핑
In [16]:
m = re.match('.*?(\d)', text)
In [17]:
if m is not None:
print([m.group(0), m.group(1)])
In [18]:
m = re.match('.*?(\d+)', text)
In [19]:
if m is not None:
print([m.group(0), m.group(1)])
In [20]:
m = re.match('(.*?)(\d+)', text)
In [21]:
if m is not None:
print([m.group(0), m.group(1), m.group(2)])
In [22]:
m = re.match('(.*?)(\d+)$', text)
In [23]:
if m is not None:
print([m.group(0), m.group(1), m.group(2)])
In [24]:
m = re.match('(.*?)([0-9\-]+)$', text)
In [25]:
if m is not None:
print([m.group(0), m.group(1), m.group(2)])
findall 메소드
In [26]:
re.findall('\d', text)
Out[26]:
In [27]:
re.findall('\d+', text)
Out[27]:
매칭된 문자열 참조
In [28]:
re.sub('(\d+)-(\d+)-(\d+)', '\\2-\\3-\\1', text)
Out[28]:
In [ ]: