정규 표현식(Regular Expression)을 사용하여 '대문자로 시작하고 그 뒤에 소문자가 이어지는' 형태의 문자열인지 확인해야 하는 경우가 있습니다. 이럴 때 match_string이라는 함수를 정의하고, 함수 내부에서 re 모듈의 search 메서드를 호출해 정규식 패턴과 문자열이 일치하는지 검사할 수 있습니다. 함수 외부에서 문자열을 정의한 뒤, 해당 문자열을 인자로 전달하며 함수를 호출하면 됩니다.
정규식 패턴의 의미
[A-Z]+: 하나 이상의 대문자가 연속으로 나타남[a-z]+: 하나 이상의 소문자가 연속으로 나타남$: 문자열의 끝을 의미하며, 소문자로 끝나야 조건에 부합함
예제 코드
아래는 실제 동작 과정을 보여주는 예시입니다.
import re
def match_string(my_string):
pattern = '[A-Z]+[a-z]+$'
if re.search(pattern, my_string):
return('The string meets the required condition \n')
else:
return('The string doesnot meet the required condition \n')
print("The string is :")
string_1 = "Python"
print(string_1)
print(match_string(string_1))
print("The string is :")
string_2 = "python"
print(string_2)
print(match_string(string_2))
print("The string is :")
string_3 = "PythonInterpreter"
print(string_3)
print(match_string(string_3))
실행 결과
The string is : Python The string meets the required condition The string is : python The string doesn't meet the required condition The string is : PythonInterpreter The string meets the required condition
코드 설명
정규식 처리를 위해 필요한
re모듈을 임포트합니다.문자열을 매개변수로 받는
match_string함수를 정의합니다.함수 내부에서는
search메서드를 사용해 지정한 정규식 패턴이 문자열 안에 존재하는지 확인합니다.패턴이 발견되면 조건을 충족한다는 메시지를, 그렇지 않으면 충족하지 않는다는 메시지를 반환합니다.
함수 외부에서 세 개의 테스트 문자열(
Python,python,PythonInterpreter)을 정의하고 콘솔에 출력합니다.각 문자열을 인자로 전달하며 함수를 호출하고, 그 결과가 콘솔에 출력됩니다.
실행 결과를 보면 첫 글자가 대문자이고 나머지가 소문자인 Python과, 중간의 대문자 이후 소문자로 끝나는 PythonInterpreter는 조건을 충족하지만, 전부 소문자인 python은 조건을 충족하지 못하는 것을 확인할 수 있습니다.