Python 从()和#x27;s

Python 从()和#x27;s,python,python-3.x,regex,Python,Python 3.x,Regex,我正在迭代的行如下所示: random text and A08524SDD here (00-04) more random text lame text (junk data) more text (08-12) more text 4000 5553 random text and numbers 44553349 (2008) random text (2005) junk text (junk) nothing important (13-15) not important (not

我正在迭代的行如下所示:

random text and A08524SDD here (00-04) more random text
lame text (junk data) more text (08-12) more text 4000 5553
random text and numbers 44553349 (2008) 
random text (2005) junk text (junk)
nothing important (13-15) not important (not important)
我试图找出如何只从括号中提取日期(范围或一年),而不从括号中提取其他随机垃圾

当前正在使用此选项,但它也会返回随机文本:

date = re.findall('\(([^)]+)', line)
编辑:字符串中的每一行我一次迭代一行。它不是一个单一的字符串。我有一个for循环,它搜索每一行并试图从每一行中提取日期范围。另外,随机文本中包含随机数,因此我不能在整个字符串中只搜索###-###或###。它必须被封装在()中

编辑2:@CarySwoveland已经回答了我最初的问题。作为奖励,我有几行看起来像这样的,如果它们也能被包括在内,那就太好了

random text and numbers 44553349 (2008 important text) 
random text (2005 important text) junk text (junk) 55555555 (08-09 important text)
nothing important (13-15) not important (not important)(2008 important text)
在以a####-####或a####开头的超过1()的行中,我需要用文本抓取它们。在大约35000行文字中,只有大约50行左右有这些随机问题,我不介意手工处理。但是,如果存在解决方案,那么最好实现它


谢谢你所有的发帖人!这对我帮助很大

像这样的东西对你有用吗

这是假设
strings
是一个行列表

def getter(string):
    return re.search(r'(\(\d{4}\)|\(\d{2}-\d{2}\))', string).group()

list(map(getter, strings))
输出:

['(00-04)', '(08-12)', '(2008)', '(2005)', '(13-15)']

根据您的编辑…如果您正在循环,只需在每行的循环中应用函数即可

您可以使用以下正则表达式

(?m)(?<=\()(?:\d{4}|\d{2}-\d{2})(?=\))

(?m)(?根据您的问题和添加的评论,我建议以下模式:

(?<=\()\d\d-?\d\d.*?(?=\))
返回:

['00-04']
['08-12']
['2008']
['2005']
['13-15']
['2008 important text']
['2005 important text', '08-09 important text']
['13-15', '2008 important text']

是的,在大多数情况下,它总是(######或(###-##)或(##-##)分隔的4位数字还是2位数字。在一些情况下,它是(##-######-#######-########文本),并拉可以添加一些东西来去掉括号,或者将其添加到搜索中。刚才看到你的评论,如果有######################################文本,这我添加了这些行,但没有返回任何结果:date=r'(?penguin,您需要转义
在lookarounds中。当我添加你的代码时,我的任何一行代码都没有返回任何内容。@JvdV我现在有了这个功能,它可以完美地返回年份,在超过1年的情况下,它可以同时返回这两个版本,这很好。但是它没有捕获任何文本。当我在演示中添加文本时,它不会显示任何内容b也是。@JvdV你太棒了!!!非常感谢!这非常好用,并且满足了我的所有要求!非常感谢你花时间来帮助我!!!
import re

lines = ['random text and A08524SDD here (00-04) more random text',
         'lame text (junk data) more text (08-12) more text 4000 5553',
         'random text and numbers 44553349 (2008)',
         'random text (2005) junk text (junk)',
         'nothing important (13-15) not important (not important)',
         'random text and numbers 44553349 (2008 important text)',
         'random text (2005 important text) junk text (junk) 55555555 (08-09 important text)',
         'nothing important (13-15) not important (not important)(2008 important text)']

for line in lines:
    print(re.findall(r'(?<=\()\d\d-?\d\d.*?(?=\))', line))
['00-04']
['08-12']
['2008']
['2005']
['13-15']
['2008 important text']
['2005 important text', '08-09 important text']
['13-15', '2008 important text']