正则表达式在字符串中重复检测 [英] Regular Expression to detect repetition within a string

查看:573
本文介绍了正则表达式在字符串中重复检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能发现用正则表达式重复号码模式?

Is it possible to detect repeated number patterns with a regular expression?

因此​​,举例来说,如果我有以下字符串034503450345,这将是可能的匹配重复序列0345?我有一种感觉,这是超出了正则表达式的范围,但我想我会反正在这里问,看看我是否错过了一些东西。

So for example, if I had the following string "034503450345", would it be possible to match the repeated sequence 0345? I have a feeling this is beyond the scope of regex, but I thought I would ask here anyway to see if I have missed something.

推荐答案

是的,你可以 - 这里是一个Python测试用例

Yes, you can - here's a Python test case

import re
print re.search(r"(\d+).*\1", "8034503450345").group(1)
# Prints 0345

正则表达式说再次找到数字部分序列,那么任何其他的东西量,那么相同的序列。

The regular expression says "find some sequence of digits, then any amount of other stuff, then the same sequence again."

在一个几乎没有 - 相关注意事项,这是我最喜欢的正则表达式中的一个 - 质数检测器:

On a barely-related note, here's one of my favourite regular expressions - a prime number detector:

import re
for i in range(2, 100):
    if not re.search(r"^(xx+)\1+$", "x"*i):
        print i

这篇关于正则表达式在字符串中重复检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆