Search code examples
regexpython-3.xpattern-recognition

Detect some special sub string with re library in python


I want to detect some special sub string and also overlapping.I have a string from input and if the string comprises 'AB' and 'BA'(both of them) I print in out 'yes' and if only comprises 'ABA' or 'BAB'(overlap) the output is 'NO'. I wrote the following code but I receive error. the problem is in re.search() in if . how can I use correctly re.search for this code? Thanks in advance for your help

import re
str1=input()
if re.search('AB',str1):
        if re.search('BA',str1):
            if re.search('ABA'|'BAB',str1):
                if re.search('ABBA'|'BAAB',str1):
                    print('YES')
                print('NO')
            print('YES')
        else :
           print('NO')
else:
      print('NO')

Solution

  • You could directly check for the pattern instead of worrying about overlap (as this is what regex is good for).

    (I have made an assumption here that a string ABAxyzBAB should print 'YES' since it contains cases of AB and BA in individual cases and not just an overlap)

    import re
    str1=input()
    if re.search(r'AB.*?BA', str1):
        print('YES')
    elif re.search(r'BA.*?AB', str1):
        print('YES')
    else:
        print('NO')
    

    What this does is, it first checks to see if a part of the string matches AB, it then looks after the AB to find a BA, if this happens it prints out 'YES'. Otherwise it tries to do the opposite, it will then check to see if part of the string matches BA, then it will look after the BA to find an AB. If it finds an AB afterwards it prints out 'YES'. In the case that neither of these happen it prints out 'NO'