简体   繁体   English

如何使用允许字符跳过的正则表达式找到字符串在文本中出现的次数

[英]How can I find how many times a string appears in a text with Regex that allows character skipping

I need to explain a little: I want to find how many "abab" exists in "ababab" string.我需要解释一下:我想找出“ababab”字符串中存在多少个“abab”。

But skipping is valid like但是跳过是有效的

[abab]ab [abab]ab

[aba]ba[b] [阿巴]巴[b]

[ab]ab[ab] [ab]ab[ab]

[a]ba[bab] [a]ba[bab]

these are all valid, my attempt was to use < /\w*?a\w*?b\w*?a\w*?b/g > which of course did not work.这些都是有效的,我的尝试是使用 < /\w*?a\w*?b\w*?a\w*?b/g > 这当然没有用。 What should I do?我应该怎么办?

Python solutions are also good for me, I thought regex would be good for this. Python 解决方案对我也有好处,我认为正则表达式对此有好处。

Edit: Marked similar question is quite different to my question编辑:标记的类似问题与我的问题完全不同

For the little testing I have done, this works:对于我所做的小测试,这是有效的:

def abab(to_check):
    return is_a(0, to_check)


def is_a(i, to_check):
    count = 0
    for index, c in enumerate(to_check):
        if c == 'a':
            count = count + is_b(i + 1, to_check[index + 1:])
    return count


def is_b(i, to_check):
    count = 0
    for index, c in enumerate(to_check):
        if c == 'b':
            if i == 2:
                count = count + 1
            else:
                count = count + is_a(i, to_check[index + 1:])
    return count


print(abab("ababab"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找某个字符在相乘字符串中出现的次数 - Finding how many times a certain character appears in a multiplied string 如何按特定字符在键中出现的次数对字典键进行排序? - How can I sort a dictionary keys by how many times a specific character appears in the key? 如何查找字符串在CSV文件中出现多少次 - How to find how many times a string appears in CSV file 查找字符串在另一个 python 中出现的次数 - Find how many times string appears in another python 如何在不计算负数的情况下找到一个数字在列表中出现的次数? - How can I find how many times a number appears in a list without counting negatives? 字符串出现在另一个字符串中的次数 - How many times string appears in another string 如果字符串中的字符连续出现 3 次,如何使 output 返回 False? - How can I make the output return False if a character in the string appears three times in a row? 如果字符串中的字符连续出现 3 次,如何返回 False - How can I return False if a character in a string appears three times in a row 如何在路径字符串中找到特殊字符以及它们出现的次数 - how do I find special character in the path string and how many times are they present 在 Python 中找出字符串中正则表达式匹配的次数 - Find out how many times a regex matches in a string in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM