정규식을 사용하여 대문자와 소문자의 순서를 찾아야 하는 경우 정규식과 일치시키기 위해 'search' 메서드를 사용하는 'match_string'이라는 메서드를 정의합니다. 메서드 외부에 문자열이 정의되어 있고 문자열을 전달하여 메서드가 호출됩니다.
예시
아래는 동일한 데모입니다.
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
설명
-
필요한 패키지를 가져옵니다.
-
문자열을 매개변수로 사용하는 'match_string'이라는 메서드가 정의되어 있습니다.
-
'search' 방법을 사용하여 문자열에서 특정 정규식이 발견되었는지 여부를 확인합니다.
-
메서드 외부에 문자열이 정의되어 콘솔에 표시됩니다.
-
이 문자열을 매개변수로 전달하여 메서드를 호출합니다.
-
출력은 콘솔에 표시됩니다.