📌  相关文章
📜  使用Python Regex 在给定字符串中查找“1(0+)1”的所有模式

📅  最后修改于: 2022-05-13 01:54:24.543000             🧑  作者: Mango

使用Python Regex 在给定字符串中查找“1(0+)1”的所有模式

字符串包含 1(0+)1 形式的模式,其中 (0+) 表示任何非空的连续 0 序列。计算所有这些模式。允许图案重叠。

注意:它只包含数字和小写字符。字符串不一定是二进制的。 100201 不是有效模式。

例子:

Input : 1101001
Output : 2

Input : 100001abc101
Output : 2

我们有解决此问题的现有解决方案,请参阅在给定字符串链接中查找“1(0+)1”的所有模式。另一套包含在Java中使用正则表达式的类似解决方案也已发布。

我们将在Python中使用 Regex 快速解决这个问题。方法很简单:

  1. 使用 re.search(regex, 字符串 ) 方法在原始字符串中搜索遵循 '10+1' 模式的第一个子字符串。
  2. substr = re.search(regex, 字符串)如果在原始字符串中没有找到给定的正则表达式作为子字符串,则返回None ,否则返回第一个匹配的子字符串,它遵循 '10+1' 模式。 substr.start()为我们提供匹配正则表达式的起始索引,而substr.end()为我们提供匹配正则表达式的结束索引。
  3. 每当我们找到正则表达式作为子字符串时,将计数增加 1 并再次从前一个子字符串的结束索引开始搜索给定的正则表达式。
# Python program to Find all the patterns 
# of “1(0+)1” in a given string using Python Regex
  
import re
  
# Function to Find all the patterns
# of “1(0+)1” in a given string
def extract(input):
  
    # search regex '10+1' in original string
    # search() function return first occurrence 
    # of regex '10+1' otherwise None
    # '10+1' means sub-string starting and ending with 1
    # and atleast 1 or more zeros in between
    count=0
    substr = re.search('10+1',input)
      
    # search for regex in original string 
    # untill we are done with complete string
    while substr!=None:
        # if we find any occurrence then increase count by 1
        count=count+1
          
        # find next occurrence just after previous 
        # sub-string
        # for first occurrence 101, substr.start()=1
        # substr.end()=4
        input = input[(substr.end()-1):]
        substr = re.search('10+1',input)
    print (count)
  
# Driver program
if __name__ == "__main__":
    input = '1101001'
    extract(input)

输出:

2