How to match start and end position of words from string with substring and regular expression in Python

1 Answer

0 votes
import re     
 
s = 'Python programming truthful wealthy java php'     
pattern = re.compile(r'\b\w*th\w*\b')   

pos = 0    
while True:         
    match_p = pattern.search(s, pos)         
    if not match_p:             
        break         
    st = match_p.start()         
    ed = match_p.end()         
    print('{:>3d} : {:>3d} = "{}"'.format(st, ed - 1, s[st:ed]))               
    pos = ed
     
     
     
'''
run:
 
  0 :   5 = "Python"
 19 :  26 = "truthful"
 28 :  34 = "wealthy"

'''

 



answered Apr 29, 2019 by avibootz
...