Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm stuck with regular expressions

I’m stuck with regular expressions in Python…

#!/usr/bin/python3
import re

combi="ABBAEAADCA"
one_a = len(re.findall('[^A](A)[^A]', combi))
print("A:"+str(one_a))

I try to make this variable (one_a) contain the number of A’s that appear alone (3) but it does not count those at the beginning and end of lines so….

one_a = len(re.findall('\A(A)[^A]', combi))
print("A ini:"+str(one_a))
one_a += len(re.findall('[^A](A)[^A]', combi))
print("A_cen:"+str(one_a))
one_a += len(re.findall('[^A](A)\Z', combi))
print("A_end:"+str(one_a))

but it didn’t work either when in this particular case the value that should stay in the variable should be 3.
I would appreciate knowing what I am missing or what mistake I am making.
Thank you very much

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine start-of-string (^) and end of string ($) with regular character classes through the or (|) operator.

re.findall(r'(?:^|[^A])A(?:$|[^A])', combi)

This gives you all substrings where A is either surrended by start of string and end of string, start of string and not-A, not-A or end of string or not-A and not-A.

>>> re.findall(r'(?:^|[^A])A(?:$|[^A])', combi)
['AB', 'BAE', 'CA']

Applying len to this list gives you the count of single A’s.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading