如何使用正则表达式查找<=AAA in Python?

问题描述 投票:0回答:2

我有以下代码

def append_letter():
  string = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'

  result = []
  # compete the pattern below
  pattern = r'(?<=AAA)\w+'
  for item in re.finditer(pattern, string):
    # identify the group number below.
    result.append(item.group(1))
  return result

如何附加未包含的字母 A 字母

从上面的脚本中,我想将任何字母后跟三个 A(包括 A)添加到列表中。

如何通过仅修改这行代码来实现这一点:

pattern = r'(?<=AAA)\w+'
python regex
2个回答
1
投票

您可以使用

re.findall
进行积极的前瞻。

>>> import re
>>> str = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'
>>> re.findall(r'.(?=AAA)', str)
['C', 'F', 'B']

或者如果您必须使用

re.finditer

>>> [match[0] for match in re.finditer(r'.(?=AAA)', str)]
['C', 'F', 'B']

无论哪种方式,匹配

AAA
后的任何字符的正确模式是:

r'.(?=AAA)'

0
投票

试试这个:

import re

def append_letter():
    string = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'

    result = []
    # Complete the pattern below
    pattern = r'(?<=AAA)\w'
    for item in re.finditer(pattern, string):
        result.append(item.group())
    return result

# Call the function and store the result
letters_following_AAA = append_letter()

# Print the result
print(letters_following_AAA)

代码输出

["B", "C", "F"]

© www.soinside.com 2019 - 2024. All rights reserved.