我的正则表达式模式在 Python 中查找重复循环有什么问题? [英] What is wrong with my regex Pattern to find recurring cycles in Python?
本文介绍了我的正则表达式模式在 Python 中查找重复循环有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想匹配任何具有重复循环的字符串.就像这个数据:
<前>3333333333333333333333333333333333333333/1位数周期(3)16666666666666666666666666666666666666666/1位数循环(6)1428571428571428571428571428571428571428/6位数周期(142857)111111111111111111111111111111111111111/1位数周期(1)0909090909090909090909090909090909090909/2位数周期(09)0834522467546323545411673445234655345222/无循环0769230769230769230769230769230769230769/6位数周期(769230)0714285714285714285714285714285714285714/6位数周期(714285)0666666666666666666666666666666666666666/1位数循环(6)我尝试过的模式是 "([0-9]+?)\1+"
它在其他语言(如 VB 或文本编辑器)中运行良好.我将这些字符串存储在名为 values
的列表中.所以这是我的代码:
导入重新#stuff 获取值pattern = re.compile("([0-9]+?)\1+")对于值中的值:matchObj = 模式.搜索(值)打印(matchObj)#->没有任何matchObj = pattern.findall(value)打印(matchObj)#->[]
我做错了什么?任何提示表示赞赏.
解决方案
添加 r 前缀:
r"([0-9]+?)\1+"
这将使反斜杠成为文字反斜杠而不是转义 1.
I want to match any string that has a recurring cycle. Like in this data:
3333333333333333333333333333333333333333 / 1 digit cycle(3) 1666666666666666666666666666666666666666 / 1 digit cycle(6) 1428571428571428571428571428571428571428 / 6 digit cycle(142857) 1111111111111111111111111111111111111111 / 1 digit cycle(1) 0909090909090909090909090909090909090909 / 2 digit cycle(09) 0834522467546323545411673445234655345222 / no cycle 0769230769230769230769230769230769230769 / 6 digit cycle(769230) 0714285714285714285714285714285714285714 / 6 digit cycle(714285) 0666666666666666666666666666666666666666 / 1 digit cycle(6)
The pattern I have tried is "([0-9]+?)\1+"
which works well in other languages (like VB or text editors). I have stored these strings inside a list named values
. So here is my code:
import re
#stuff to get values
pattern = re.compile("([0-9]+?)\1+")
for value in values:
matchObj = pattern.search(value)
print(matchObj) #-> None
matchObj = pattern.findall(value)
print(matchObj) #-> []
What am I doing wrong? Any hint is appreciated.
解决方案
Add an r prefix:
r"([0-9]+?)\1+"
That will make the backslash a literal backslash instead of escaping the 1.
这篇关于我的正则表达式模式在 Python 中查找重复循环有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文