在Python中如何用regex区分重叠的字符串?

2024-10-03 02:39:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出一个序列中所有四个字母的字符串。第一个字母是“N”,第二个不是“P”,第三个是“S”或“T”,最后一个不是“P”。你知道吗

这是我的密码:

import re
seq='NNSTQ'
glyco=re.findall('N[^P][S|T][^P]',seq)
print glyco

结果是:

['NNST']

但是,预期产出应为:

['NNST','NSTQ']

我认为问题是这两个弦的部分重叠了,而且关于芬德尔()跳过第二个。我能做些什么来解决它?你知道吗


Tags: 字符串importre密码字母序列seqprint
2条回答

findall()不返回重叠的匹配,但是没有什么可以阻止您显式搜索它们,例如:

def myfindall(p, s):
 found = []
 i = 0
 while True:
  r = re.search(p, s[i:])
  if r is None:
   break
  found.append(r.group())
  i += r.start()+1
 return found

seq='NNSTQ'
glyco=myfindall('N[^P][ST][^P]', seq)

您应该改用(?=...)(lookahead断言),因为只有findall匹配项才使用字符串部分一次,means忽略重叠:

import re
seq='NNSTQ'
glyco=re.findall('(?=(N[^P][S|T][^P]))',seq)
print (glyco) 
# prints ['NNST','NSTQ']

这将匹配所有内容,即使它重叠。正如doc所述:

(?=...)

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

您还可以查看此项以了解更多信息:

http://regular-expressions.mobi/lookaround.html?wlr=1

相关问题 更多 >