import re
data = """ *** Section with no sub section
*** Section with sub section ***
*** Sub Section ***
*** Another section"""
pattern = r'^[ ]{0,2}(?:[*]{3}[ ]?(?P<Section>.*?)|[ ]+[*]{3}[ ]?(?P<SubSection>.*?))(?:[ ]?[*]{3})?$'
regex = re .compile ( pattern, re .M )
for match in regex.finditer ( data) :
print ( match.groupdict ( ) )
''' OUTPUT:
{'Section': 'Section with no sub section', 'SubSection': None}
{'Section': 'Section with sub section', 'SubSection': None}
{'Section': None, 'SubSection': 'Sub Section'}
{'Section': 'Another section', 'SubSection': None}
'''
aW1wb3J0IHJlCgpkYXRhID0gIiIiICAqKiogU2VjdGlvbiB3aXRoIG5vIHN1YiBzZWN0aW9uCiAgKioqIFNlY3Rpb24gd2l0aCBzdWIgc2VjdGlvbiAqKioKICAgICAgICAgICAqKiogU3ViIFNlY3Rpb24gKioqCiAgKioqIEFub3RoZXIgc2VjdGlvbiIiIgoKcGF0dGVybiA9IHInXlsgXXswLDJ9KD86WypdezN9WyBdPyg/UDxTZWN0aW9uPi4qPyl8WyBdK1sqXXszfVsgXT8oP1A8U3ViU2VjdGlvbj4uKj8pKSg/OlsgXT9bKl17M30pPyQnCnJlZ2V4ID0gcmUuY29tcGlsZShwYXR0ZXJuLCByZS5NKQoKZm9yIG1hdGNoIGluIHJlZ2V4LmZpbmRpdGVyKGRhdGEpOgoJcHJpbnQobWF0Y2guZ3JvdXBkaWN0KCkpCgonJycgT1VUUFVUOgp7J1NlY3Rpb24nOiAnU2VjdGlvbiB3aXRoIG5vIHN1YiBzZWN0aW9uJywgJ1N1YlNlY3Rpb24nOiBOb25lfQp7J1NlY3Rpb24nOiAnU2VjdGlvbiB3aXRoIHN1YiBzZWN0aW9uJywgJ1N1YlNlY3Rpb24nOiBOb25lfQp7J1NlY3Rpb24nOiBOb25lLCAnU3ViU2VjdGlvbic6ICdTdWIgU2VjdGlvbid9CnsnU2VjdGlvbic6ICdBbm90aGVyIHNlY3Rpb24nLCAnU3ViU2VjdGlvbic6IE5vbmV9CicnJw==