Mathlife
Mathlife의 학습 노트
Mathlife
전체 방문자
오늘
어제
  • 분류 전체보기
    • CS
      • 알고리즘
      • 자료구조
      • 운영체제
      • 네트워크
      • 데이터베이스
    • 프로그래밍 언어
      • Java
      • JavaScript
      • C·C++
      • Python
    • Backend
      • Spring
    • Frontend
      • HTML
      • CSS
    • Math
      • Linear Algebra
      • Calculus
    • AI
      • ML
      • DL
      • RL
    • Git

블로그 메뉴

  • 홈
  • 관리
  • 글쓰기
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Mathlife

Mathlife의 학습 노트

파이썬 re
프로그래밍 언어/Python

파이썬 re

2022. 6. 20. 21:26

1. methods

 

re.match(pattern, string, flags)

re.search(pattern, string, flags)

re.findall(pattern, string, flags)

 

re.sub(pattern, repl, string, count, flags)

- repl : string or function. (치환 후의 문자열) or  (matchObject -> 치환 후의 문자열).

- count는 최대 몇 개를 치환할지를 지정

- ex) 비밀번호 앞에 4자리만 보여주기

re.sub("^(\d{4})(\d+)", lambda m : m.group(1)+"*"*len(m.group(2)), password)

 

re.split(patter, string, maxsplit, flags) : maxsplit은 최대 몇 번 자를지 지정

 

2. match object

import re

matchObj = re.search('test', 'this is a test sentence.')
print(matchObj)
print(matchObj.group())
print(matchObj.start())
print(matchObj.end())
print(matchObj.span())

 

group()은 일치하는 패턴을 반환, groups는 캡쳐한 group tuple을 반환

findall은 캡쳐가 있다면 list of patterns가 아니라 list of group tuples를 반환

import re

matchObj = re.search('(\d{4})-(\d{1,2})-(\d{1,2})', '2018-3-4 2019-11-17')
print(matchObj)
print(matchObj.group())
print(matchObj.groups())

print("-"*30)

matchObj = re.findall('(\d{4})-(\d{1,2})-(\d{1,2})', '2018-3-4 2019-11-17')
print(matchObj)

 

3. \d, \D, \w, \W, \s, \S

 

\d : 숫자

\w : 영문 대소문자, 숫자, _(언더바), 한글(파이썬의 경우), ...

\s : space, \t, \n

 

\D : \d의 반대

\W : \w의 반대 (공백, 특수문자)

\S : \s의 반대

 

4. ^, $, \A, \Z

By default,

 

^, $  : 문자열의 시작과 끝에 매치

\A, \Z : 문자열의 시작과 끝에 매치

 

하지만 re.M 혹은 re.MULTILINE 플래그를 적용시키면,

 

^, $ : 행의 시작과 끝에 매칭

 

import re

print(re.findall('\Ahello', 'hello\nhello\nhello'))
print(re.findall('^hello', 'hello\nhello\nhello'))
print(re.findall('^hello', 'hello\nhello\nhello', re.MULTILINE))

 

 

Reference.

 

https://greeksharifa.github.io/%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D(re)/2018/07/20/regex-usage-01-basic/ 

 

Python, Machine & Deep Learning

Python, Machine Learning & Deep Learning

greeksharifa.github.io

 

'프로그래밍 언어 > Python' 카테고리의 다른 글

파이썬 concatenation  (0) 2022.06.13
파이썬 reduce  (0) 2022.06.12
파이썬 cmp_to_key  (0) 2022.06.10
파이썬 any, all  (0) 2022.06.10
파이썬 진법 변환  (0) 2022.06.09
    '프로그래밍 언어/Python' 카테고리의 다른 글
    • 파이썬 concatenation
    • 파이썬 reduce
    • 파이썬 cmp_to_key
    • 파이썬 any, all
    Mathlife
    Mathlife

    티스토리툴바