找一个由三个大写字母环绕的小写字母

2024-05-18 23:28:14 发布

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

我有一个混合了大小写字母的字符串。我需要找到每一个由3个大写字母环绕的小写字母,并从字符串中提取出来。在

例如,ZZZaZZZ我想提取前一个字符串中的a。在

我编写了一个脚本,它能够提取ZZZaZZZ,但不能单独提取{}。我知道我需要使用嵌套的regex表达式来实现这一点,但我无法完全考虑如何实现这一点。以下是我所拥有的:

import string, re                                                                                                                                                                

if __name__ == "__main__":                                                                                                                                                       

    #open the file                                                                                                                                                               
    eqfile = open("string.txt")                                                                                                                                                
    gibberish = eqfile.read()                                                                                                                                                    
    eqfile.close()                                                                                                                                                               

    r = re.compile("[A-Z]{3}[a-z][A-Z]{3}")                                                                                                                                      
    print r.findall(gibberish)           

编辑: 谢谢你们的回答!我想我应该说得更具体些。我需要找到由三个完全相同的大写字母包围的小写字母,例如在我的示例ZZZaZZZ。在


Tags: 字符串nameimportre脚本stringif表达式
3条回答
r = re.compile("(?<=[A-Z]{3})[a-z](?=[A-Z]{3})") 

(?<=...)表示正向后看,(?=...)表示正向展望。在

module re

(?=...)

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'.

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position.

您需要用括号捕获您感兴趣的字符串部分,然后用re.MatchObject#group访问它:

r = re.compile("[A-Z]{3}([a-z])[A-Z]{3}")                                                                                                                                      
m = r.match(gibberish)
if m:
   print "Match! Middle letter was " + m.group(1)           
else:
   print "No match."

你已经很接近了!阅读MatchObjects.group*方法。例如,如果您的脚本以

r = re.compile("[A-Z]{3}([a-z])[A-Z]{3}")
print r.match(gibberish).group(1)

然后在第一组中捕捉所需的角色。在

要解决匹配重复字母的新限制,可以使用反向引用:

^{pr2}$

读起来像:

  1. 匹配字母a-Z并记住它。在
  2. 匹配找到的第一个字母的两个匹配项。在
  3. 匹配您的小写字母并将其存储在名为middle的组中。在
  4. 匹配找到的第一个字母的另外三个连续实例。在
  5. 如果找到匹配项,则打印middle组的值。在

相关问题 更多 >

    热门问题