[英]Find pattern in python string with flexible length of each pattern component
我有一個字符串:
str_x = "121001221122010120211122211122222222112222"
我想找出在字符串中觀察到給定模式多少次,但該模式應被視為靈活的 :
因此,我正在尋找的模式是:
因此,滿足該條件的圖案例如將是“ 22211222”,也將是“ 2222111222”和“ 222222221111111111111222”
我想找出在str_x中看到了多少次“靈活模式”。
正確的答案是2次。
任何想法如何做到這一點? 謝謝你
編輯
給定我上面的定義,兩次回答實際上是不正確的,因為有效的模式重疊了……例如“ 222111222”,“ 2221112222”,“ 22211122222”等都是滿足目標的模式。
我想要的是找到不重疊的模式數量(即仍然是2倍)
您必須使用正則表達式來解決您的問題: https : //docs.python.org/2/library/re.html
正則表達式:
regex = r"2{3,}?1{2,}?2{3,}?"
意思是=找到至少三個2,然后是至少兩個1,然后是至少三個2
符號2{3,}
表示找到至少三個2
?
手段-貪婪的搜索-可能重疊的搜索
如果要查找不重疊的圖案-只需刪除?
import re
regex = r"2{3,}?1{2,}?2{3,}?"
test_str = "121001221122010120211122211122222222112222"
matches = re.finditer(regex, test_str)
for matchNum, match in enumerate(matches):
matchNum = matchNum + 1
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
print ("total matches: {matches}".format(matches= matchNum))
這是一段有效的代碼:
def count_pattern(str):
# one_count keeps count of contiguous 1s
# we check for the pattern at 2 just after a block of 1s
# count keeps track of pattern counts
count=0
one_count=0
for i in range(1,len(str)):
if str[i]=='1':
if str[i-1]=='1':
one_count=one_count+1
else:
one_count=1
elif (str[i]=='2')&(str[i-1]=='1')&(len(str)-i>2)&
(i>one_count+2)&(one_count>1)&(str[(i+1):(i+3)]=='22')&
(str[(i-one_count-3):(i-one_count)]=='222'):
count=count+1
return(count)
print("Number of times the pattern
occurs=",count_pattern('121001221122010120211122211122222222112222'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.