Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find specific letter before a condition Python

Tags:

python

regex

I just want to find all characters (other than A) which are followed by triple A, i.e., have AAA to the right. I don’t want to include the triple A in the output and just want the character immediately preceding 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

I just need find this letters in []

'ACAABAA[C]AAABACDBADDDFSDDDFFSSSASDA[F]AAAC[B]AAAFASD'
like image 891
Koza Avatar asked Feb 06 '26 05:02

Koza


1 Answers

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

The negative lookahead asserts that what is directly to the right is not tripple A, but you want the opposite.

You can match a single B-Z and assert what is directly to the right is AAA

[B-Z](?=AAA)

Regex demo | Python demo

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

import re

s = 'ACAABAACAAABACDBADDDFSDDDFFSSSASDAFAAACBAAAFASD'
pattern = r'[B-Z](?=AAA)'
result = re.findall(pattern, s)

print(result)

Python demo

like image 139
The fourth bird Avatar answered Feb 09 '26 12:02

The fourth bird