반응형

정규식

정규식은 문자열에 대해 다양한 유형의 작업을 수행하는 데 사용됩니다.

Python의 정규식은 패턴과 함수의 두 부분으로 구성됩니다. 정규식 패턴은 문자열 내에서 패턴을 검색하는 데 사용되는 반면 함수는 패턴에서 반환된 문자열에 대한 작업을 수행하는 데 사용됩니다.

Python에서 정규식을 사용하려면 re 모듈을 가져와야 합니다. 아주 간단한 정규식의 예를 살펴보겠습니다.

다음 스크립트는 "^p.*y$" 패턴을 사용하여 정규식을 만듭니다. 이 정규식은 문자 p로 시작하고 문자 y로 끝나는 모든 문자열과 일치합니다.

다음 스크립트에서 정규 표현식에 사용되는 함수는 match()로 문자열이 정규 표현식에 지정된 패턴과 일치하면 True를 반환합니다.

match 함수의 첫 번째 매개변수는 검색할 패턴이고 두 번째 매개변수는 패턴을 검색하려는 문자열입니다.

 

import re

 

pattern = '^p.*y$'

string_list = ["pathology", "biology", "geography", "psychology", "mathematics"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

psychology

 

메타 문자를 사용하여 패턴 지정

메타 문자는 정규식 패턴을 정의하는 데 사용되는 특수 문자입니다.

 

대괄호 []

대괄호는 문자열에서 여러 패턴을 검색할 때 사용합니다.

다음 스크립트의 패턴은 문자열의 아무 곳에나 문자 a 또는 b가 포함된 모든 문자열을 반환합니다.

 

import re

 

pattern = '.*[ab].*'

string_list = ["pathology", "biology", "geography", "psychology", "mathematics"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

biology

geography

mathematics

 

마침표

마침표는 특정 위치의 문자를 검색하는 데 사용됩니다.

다음 스크립트는 문자열에서 5개 이상의 문자가 있는 모든 문자열을 검색합니다.

 

import re

 

pattern = '.....'

string_list = ["pathology", "bio", "geography", "psychology", "mathematics", "nic"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

geography

psychology

mathematics

 

캐럿(^)과 달러($)

캐럿 기호는 문자열의 시작 부분에서 문자 또는 문자열을 검색하는 반면 달러 기호는 다른 문자열의 끝에서 문자 또는 문자열을 검색하는 데 사용됩니다.

예를 들어, 다음 스크립트의 정규식은 알파벳 p로 시작하고 그 뒤에 임의의 수의 문자(.*)가 오고 알파벳 y로 끝나는 모든 문자열을 반환합니다.

 

import re

 

pattern = '^p.*y$'

string_list = ["pathology", "bio", "geography", "psychology", "mathematics", "nic"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

psychology

 

더하기(+)

더하기 기호는 기호 왼쪽에서 하나 이상의 패턴 발생을 검색하는 데 사용됩니다. 예를 들어, 패턴 ".*og+y" y로 끝나고 문자 o를 포함하는 모든 문자열과 y앞에 g가 하나 이상 오는 패턴을 검색합니다.

 

import re

 

pattern = '.*og+y'

string_list = ["pathology", "bio", "geography", "psychology", "mathematics", "nic"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

psychology

 

물음표(?)

반면에 물음표 기호는 기호 오른쪽에서 하나 이상의 패턴 발생을 검색하는 데 사용됩니다.

 

import re

 

pattern = '.*at?h'

string_list = ["pathology", "bio", "geography", "psychology", "mathematics", "nic"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathology

mathemathics

 

변경(|) 및 그룹화()

변경 기호(|)는 둘 이상의 정규식 패턴 사이에 OR 조건을 지정하는 데 사용됩니다. 그룹화 기호()는 두 개 이상의 패턴을 그룹화하는 데 사용됩니다.

예를 들어 "(^p) | (.*s$)”는 문자 p로 시작하거나 문자 s로 끝나는 모든 문자열과 일치합니다.

 

import re

 

pattern = '(^p)|(.*s$)'

string_list = ["pathologggy", "bio", "geography", "psychology", "mathematics", "nic"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

pathologggy

psychology

mathematics

 

백슬래시

백슬래시는 일반적으로 패턴에서 메타 문자로 사용되는 특수 문자를 사용할 수 있도록 합니다.

예를 들어 문자열 내에서 점 기호를 검색하려면 \를 통해 검색할 수 있습니다. 예를 들어 다음 스크립트의 패턴은 "25."로 시작하는 모든 문자열을 반환합니다.

 

import re

 

pattern = '25\.+.*'

string_list = ["pathologggy", "25", "geography", "psychology", "mathematics", "25.34"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

25.34

 

특수 시퀀스

Python 정규 표현식에는 일부 특수 시퀀스도 포함되어 있습니다.

예를 들어, \A 패턴은 시작 부분에서 문자열을 검색합니다. 예를 들어, 다음 스크립트는 pat로 시작하는 문자열과 일치합니다.

 

import re

 

pattern = '\Aabc'

string_list = ["abcdef", "25", "xyzabcdef", "mathematics", "25.34"]

 

for str in string_list:

  result = re.match(pattern, str)

  if result:

    print(str)

 

Output:

abcdef

 

\d+ 연산자는 문자열 내의 모든 숫자를 검색합니다.

다음은 예입니다.

 

import re

 

pattern = '\d+'

str = "This is 10, he is 22"

 

result = re.findall(pattern, str)

print(result)

 

Output:

[‘10’, ‘22’]

 

대문자 D가 있는 \D+ 시퀀스는 숫자를 제외한 문자열의 모든 단어를 반환합니다. 다음 예를 보십시오.

 

import re

 

pattern = '\D+'

str = "This is 10, he is 22"

 

result = re.findall(pattern, str)

print(result)

 

Output:

['This is ', ', he is ']

 

\w+ 시퀀스는 문자열 내의 특수 문자를 제외한 모든 단어를 반환합니다.

 

import re

 

pattern = '\w+'

str = "This is 10% he is # 22"

 

result = re.findall(pattern, str)

print(result)

 

Output:

['This', 'is', '10', 'he', 'is', '22']

 

대문자 W가 있는 \W+는 문자열 내에서 특수 문자만 반환합니다.

 

import re

 

pattern = '\W+'

str = "This is 10% he is # 22"

 

result = re.findall(pattern, str)

print(result)

 

Output:

[' ', ' ', '% ', ' ', ' # ']

 

함수의 정규 표현식

findall() 함수

findall() 함수는 특정 패턴과 일치하는 문자열의 모든 단어를 일치시키고 반환합니다.

 

import re

 

pattern = '\d+'

str = "This is 10 he is 22 and the gate is 80"

 

result = re.findall(pattern, str)

print(result)

 

Output:

['10', '22', '80']

 

split() 함수

split() 함수는 정규 표현식과 일치하는 위치에서 문자열을 분할합니다.

예를 들어 다음 스크립트의 정규식은 숫자가 있는 문자열을 분할합니다.

 

import re

 

pattern = '\d+'

str = "This is 10 he is 22 and the gate is 80."

 

result = re.split(pattern, str)

print(result)

 

Output:

['This is ', ' he is ', ' and the gate is ', '.']

 

sub() subn() 함수

sub() 함수는 지정된 패턴과 일치하는 위치에서 문자열을 다른 문자열로 대체합니다.

예를 들어, 다음 스크립트는 문자열의 모든 숫자를 문자열 XX로 바꿉니다.

 

import re

 

pattern = '\d+'

str = "This is 10 he is 22 and the gate is 80."

 

result = re.sub(pattern, 'XX', str)

print(result)

 

Output:

This is XX he is XX and the gate is XX.

 

subn() 함수는 sub() 함수와 매우 유사합니다.

그러나 업데이트된 문자열 외에도 subn() 함수는 대체 횟수도 반환합니다.

예를 들어, 다음 스크립트에서 subn() 함수는 출력에 표시된 대로 세 번 대체합니다.

 

import re

 

pattern = '\d+'

str = "This is 10 he is 22 and the gate is 80."

 

result = re.subn(pattern, 'XX', str)

print(result)

 

Output:

(‘This is XX he is XX and the gate is XX.’, 3)

 

search()

search() 메서드는 문자열 내에서 패턴을 검색하고 처음 일치하는 패턴의 값과 인덱스를 반환합니다.

예를 들어 다음 스크립트는 문자열 내에서 숫자를 검색합니다. 첫 번째 숫자가 10이므로 해당 값, 10과 해당 인덱스(8-10)가 반환됩니다.

 

import re

 

pattern = '\d+'

str = "This is 10 he is 22 and the gate is 80."

 

result = re.search(pattern, str)

print(result)

 

Output:

<re.Match object; span=(8, 10), match='10'>

반응형

+ Recent posts