Find all the patterns of “1(0+)1” in a given string using Python Regex
本教程中,我們將編寫一個程式,該程式使用regexes查詢字串中所有出現 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']
結論
如果您對本教程有任何疑問,可以在評論部分中提出來。
廣告
資料結構
聯網
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP