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

結論

如果您對本教程有任何疑問,可以在評論部分中提出來。

更新時間: 23-Oct-2019

184 次觀看

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.