Python/Python Programming

[Python] 정규식 전방탐색과 후방탐색을 이용한 문자열 분할

Pydole 2018. 5. 13. 00:34

 

DOCS : https://docs.python.org/3/library/re.html

 

 

 로그파일이 일정한 구분자 (콤마(,), 공백, 세미콜론(;)) 로 구분되어 있으면 리스트나 튜플이 인덱싱을 이용하여

쉽게 분석할 수 있다.

 

 하지만 비정형 로그 분석 혹은 모든 이벤트에 따라 로그형식이 일정치 않다면 파이썬 정규식의 기능인

"전방탐색"과 "후방탐색"을 통해 분할 할 수 있다.

 


 

예제 텍스트 파일)

 

2018-05-12 00:00:01 ABC DEFG log: this is python

2018-05-12 00:00:02 ABC DEFG HI log: this is python

2018-05-12 00:00:03 ABC DEFG HI JKL log: this is python

----------------------------------------------------------------------

 

 

 

 

 

1. 전방탐색 (lookahead assertion) - log: 앞부분

 

p = re.compile('.+(?=log:)')

with open(r'D:\Log\test.txt', 'r') as f:
    for x in f.readlines():
        m = p.search(x)
        print(m.group())
2018-05-12 00:00:01 ABC DEFG 
2018-05-12 00:00:02 ABC DEFG HI 
2018-05-12 00:00:03 ABC DEFG HI JKL 
 

 

2. 후방탐색( positive lookbehind assertion) - log: 뒷부분

 

import re

p = re.compile('(?<=log:).+')

with open(r'D:\Log\test.txt', 'r') as f:
    for x in f.readlines():
        m = p.search(x)
        print(m.group())
 this is python
 this is python
 this is python