import re pattern = re.compile(r'(\w+)?([.,#])((?(1)\w*|\w+))') strings = ['no.16', '#400', 'word1.word2', 'word', '123'] for s in strings: print(s, ' -> ', pattern.findall(s))
Standard input is empty
no.16 -> [('no', '.', '16')]
#400 -> [('', '#', '400')]
word1.word2 -> [('word1', '.', 'word2')]
word -> []
123 -> []