python正则表达式模式re.search

时间:2015-10-14 13:41:38

标签: python

你好我对python正则表达式感到困惑,这是我的代码:

import os,re,sys

t="LOC_Os01g01010.1 GO:0030234  F   enzyme regulator activity   IEA     TAIR:AT3G59570"
k =['LOC_Os01g01010']

re_search=re.search(re.escape(k[0] + r'.1   GO:\d{7}'),t,re.M|re.I|re.S)
if re_search is None:
      pass
else:
      print re_search.group()

" T"是我的数据和" k"是我的目标。

我想要的是" LOC_Os01g01010.1 GO:0030234"或" GO:0030234"但我不知道如何编写模式。

3 个答案:

答案 0 :(得分:0)

鉴于你的例子和期望在LOC_********.*中星星可以是集合中的任何东西[a-zA-Z0-9],我建议:

import os,re,sys

t="LOC_Os01g01010.1 GO:0030234  F   enzyme regulator activity   IEA      TAIR:AT3G59570"
k =['LOC_Os01g01010']

re_search=re.search("(LOC_[0-9A-Z]*)",t,re.M|re.I|re.S)
if re_search is None:
      pass
else:
      print re_search.group()
当我使用python2.7运行时,

python regexthing.py会产生LOC_Os01g01010(LOC_[0-9A-Za-z]*)是一个捕获组,用于捕获与表达式LOC_[0-9A-Z]*匹配的任何内容。此表达式将与LOC_LOC_ABCabc123LOC_a1B2C等匹配

我希望这能回答你的问题。

答案 1 :(得分:0)

我相信以下内容可以解决您的问题:

import re
t="LOC_Os01g01010.1 GO:0030234  F   enzyme regulator activity   IEA     TAIR:AT3G59570"
my_regex = re.compile(r'^LOC_(.)*GO:\d{7}',re.M|re.I|re.S)
searches = my_regex.search(t)
if searches:
    print searches.group()

答案 2 :(得分:0)

如果有任何解决方案,那么(可证明)正则表达式有无限解决方案,可以与无限制字符串中的有限示例集合匹配。

这是一种表达方式,表示您需要更具体,因为只给我们一个您要匹配的示例,我们将为您提供多种解决方案,具体取决于进一步(未指定)我们添加自己的假设。

以下是一些假设的假设:

>>> import re
>>> t = "LOC_Os01g01010.1 GO:0030234  F   enzyme regulator activity   IEA     TAIR:AT3G59570"
>>> re.findall('\w+\.\d+', t) # any alphnumeric sequence, followed by dot and digits
['LOC_Os01g01010.1']
>>> re.findall('[A-Z]+_\w+\.\d+', t) # forcing token to start with capitals and underscore
['LOC_Os01g01010.1']
>>> re.findall('[A-Z]+_O[a-z01]+\.\d+', t) # forcing "O", and middle part to be only small letters and 0s and 1s
['LOC_Os01g01010.1']
>>> re.findall('^[A-Z]+_O[a-z01]+\.\d+', t) # forcing the pattern to be at the beginning of the string
['LOC_Os01g01010.1']```

相关问题