Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python {}不起作用的正则表达式_Python_Regex_Python 3.x - Fatal编程技术网

Python {}不起作用的正则表达式

Python {}不起作用的正则表达式,python,regex,python-3.x,Python,Regex,Python 3.x,我正在尝试匹配以下代码中出现的两次以上的haha。但是()似乎是在分组工作。为什么不起作用 >>> pattern="this is a joke hahahahahaaa. I cannot stop laughing hahahaaa" >>> print(re.findall("(ha){2,}",pattern)) ['ha', 'ha'] 我希望结果是: ['hahahaha', 'hahaha'] 我怎么修理它 import re s = '

我正在尝试匹配以下代码中出现的两次以上的
haha
。但是
()
似乎是在分组工作。为什么不起作用

>>> pattern="this is a joke hahahahahaaa. I cannot stop laughing hahahaaa"
>>> print(re.findall("(ha){2,}",pattern))
['ha', 'ha']
我希望结果是:

['hahahaha', 'hahaha']
我怎么修理它

import re

s = '"this is a joke hahahahahaaa. I cannot stop laughing hahahaaa"'
result = re.findall(r'(?:ha){2,}', s)

print(result)
输出:

['hahahahaha', 'hahaha']

  • (?:ha){2,}
    -逐字匹配序列
    ha
    (包含在组
    (..)
    )2次或更多次
    {2,}
    ,但将其视为非捕获组

  • (?:…)
    -匹配而不捕获所包含的所有内容


((?:ha){2,})
将起作用。(已编辑)@GalAbra不会抓住整个群体。它应该是
['hahahaha','hahaha']
什么是?:在这里做什么,`(r'((?:ha){2,}),s)`@Webair,添加explanation@RomanPerekhrest为什么非捕获组在这里有帮助?(我知道,但我认为最好在答案中包括)我对一件事感到困惑。。。当我这样做时,`pattern=“这是一个笑话哈哈哈哈哈哈哈。我忍不住笑哈哈哈”打印(re.findall(r)((ha){2,})”,pattern))为什么它给出:[('hahahahaha','ha'),('hahaha','ha')]`第二个元素'ha'?这是怎么回事coming@Webair,因为在后一种情况下,您有两个捕获的组:一个是完整匹配的
r'(..)
,另一个是序列
(ha)
。在视觉上,您可以观察到一个组嵌套在另一个组中,但在生成匹配结果时,它们都是单独考虑的