search 메소드


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))


1

In [6]:
s = re.search('\d', text)

In [7]:
if s is not None:
    print(s.group(0))


1

timeit 매직 커맨드를 이용한 속도 비교


In [8]:
%timeit -n 100 p.search(text)


100 loops, best of 3: 540 ns per loop

In [9]:
%timeit -n 100 re.search('\d', text)


100 loops, best of 3: 1.03 µs per loop

match 메소드


In [10]:
m = re.match('\d', text)

In [11]:
m is None


Out[11]:
True

In [12]:
m = re.match('.*\d', text)

In [13]:
if m is not None:
    print(m.group())


Learning Python 101: 2016-07-14

In [14]:
m = re.match('.*?\d', text)

In [15]:
if m is not None:
    print(m.group())


Learning Python 1

매칭 문자열 그룹핑


In [16]:
m = re.match('.*?(\d)', text)

In [17]:
if m is not None:
    print([m.group(0), m.group(1)])


['Learning Python 1', '1']

In [18]:
m = re.match('.*?(\d+)', text)

In [19]:
if m is not None:
    print([m.group(0), m.group(1)])


['Learning Python 101', '101']

In [20]:
m = re.match('(.*?)(\d+)', text)

In [21]:
if m is not None:
    print([m.group(0), m.group(1), m.group(2)])


['Learning Python 101', 'Learning Python ', '101']

In [22]:
m = re.match('(.*?)(\d+)$', text)

In [23]:
if m is not None:
    print([m.group(0), m.group(1), m.group(2)])


['Learning Python 101: 2016-07-14', 'Learning Python 101: 2016-07-', '14']

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)])


['Learning Python 101: 2016-07-14', 'Learning Python 101: ', '2016-07-14']

findall 메소드


In [26]:
re.findall('\d', text)


Out[26]:
['1', '0', '1', '2', '0', '1', '6', '0', '7', '1', '4']

In [27]:
re.findall('\d+', text)


Out[27]:
['101', '2016', '07', '14']

매칭된 문자열 참조


In [28]:
re.sub('(\d+)-(\d+)-(\d+)', '\\2-\\3-\\1', text)


Out[28]:
'Learning Python 101: 07-14-2016'

In [ ]: