[英]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.