[英]Regex to find specific letter before a condition Python
I just want to find all characters (other than A) which are followed by triple A, ie, have AAA to the right.我只想找到后跟三个 A 的所有字符(A 除外),即右侧有 AAA。 I don't want to include the triple A in the output and just want the character immediately preceding AAA
我不想在输出中包含三个 A,只想要 AAA 之前的字符
result = []
s = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'
pattern = "r'(\w[BF])(?!AAA)'"
for item in re.finditer(pattern, s):
result.append(item.group())
print(result)
I used this pattern r'(\\w[BF])(?!AAA)' but didn't worked我使用了这种模式 r'(\\w[BF])(?!AAA)' 但没有用
I just need find this letters in []我只需要在 [] 中找到这些字母
'ACAABAA[C]AAABACDBADDDFSDDDFFSSSASDA[F]AAAC[B]AAAFASD'
In your example, you want to match a single character at the left of tripple A. Using \\w[BF]
matches at least 2 characters being 1 word character followed by either B
or F
在您的示例中,您希望匹配三元组 A 左侧的单个字符。使用
\\w[BF]
匹配至少 2 个字符,即 1 个单词字符后跟B
或F
The negative lookahead asserts that what is directly to the right is not tripple A, but you want the opposite.负前瞻断言直接在右边的不是三元组 A,但你想要相反的。
You can match a single BZ and assert what is directly to the right is AAA您可以匹配单个 BZ 并断言直接在右侧的是 AAA
[B-Z](?=AAA)
Regex demo |正则表达式演示| Python demo
Python 演示
import re
result = []
s = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'
pattern = r'[B-Z](?=AAA)'
for item in re.finditer(pattern, s):
result.append(item.group())
print(result)
Output输出
['C', 'F', 'B']
You could also use re.findall你也可以使用re.findall
import re
s = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'
pattern = r'[B-Z](?=AAA)'
result = re.findall(pattern, s)
print(result)
[^A](?=A{3})
这里我使用正向前瞻。
Here is your problem's solution:这是您的问题的解决方案:
pattern = "([B-Z]{1})(A{3})"
for item in re.finditer(pattern, s):
result.append(item.group(1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.