Computer >> Máy Tính >  >> Lập trình >> Python

Tìm tất cả các mẫu của “1 (0+) 1” trong một chuỗi đã cho bằng cách sử dụng Python Regex

Trong hướng dẫn này, chúng ta sẽ viết một chương trình tìm tất cả các lần xuất hiện của 1 (0 + 1) trong một chuỗi bằng cách sử dụng regexes . Chúng tôi có một mô-đun lại bằng Python giúp chúng tôi làm việc với các biểu thức chính quy.

Hãy xem một trường hợp mẫu.

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']

Làm theo các bước dưới đây để viết mã cho chương trình.

Thuật toán

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.

Hãy xem mã.

Ví dụ

# 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)

Đầu ra

Nếu bạn chạy đoạn mã trên, bạn sẽ nhận được kết quả sau.

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

Kết luận

Nếu bạn có bất kỳ nghi ngờ nào về hướng dẫn, hãy đề cập đến chúng trong phần bình luận.