Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Regex를 사용하여 주어진 문자열에서 "1(0+)1"의 모든 패턴 찾기

<시간/>

이 튜토리얼에서는 정규식을 사용하여 문자열에서 1(0+1)의 모든 항목을 찾는 프로그램을 작성할 것입니다. . 정규 표현식으로 작업하는 데 도움이 되는 Python에 re 모듈이 있습니다.

한 가지 사례를 살펴보겠습니다.

Input:
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output:
Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']

아래 단계에 따라 프로그램 코드를 작성하세요.

알고리즘

1. Import the re module.
2. Initialise a string.
3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string.
4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method.
5. The above steps return a match object and print the matched patterns using match_object.group() method.

코드를 봅시다.

# importing the re module
import re
# initializing the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# creating a regex object for our patter
regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1
# storing all the matches patterns in a variable using regex.findall() method
result = regex.findall(string) # result is a match object
# printing the frequency of patterns
print(f"Total number of pattern maches are {len(result)}")
print()
# printing the matches from the string using result.group() method
print(result)

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

Total number of pattern maches are 3
['1(0+)1', '1(0+)1', '1(0+)1']

결론

튜토리얼에 대해 궁금한 점이 있으면 댓글 섹션에 언급하세요.