fork download
  1. import re
  2. def testReplaceBetweenWords():
  3.  
  4. head_dlmt='Head'
  5. tail_dlmt='Tail'
  6.  
  7. line0 = "abc_Head_def_Head_inner_inside_Tail_ghi_Tail_jkl"
  8. line1 = "abc_Head_first_Tail_ghi_Head_second_Tail_opq"
  9.  
  10. between_pattern = "^((?:(?!{1}).)*{0}).*?({1}.*)$".format(head_dlmt, tail_dlmt)
  11. print(between_pattern)
  12. compiled_pattern = re.compile(between_pattern)
  13.  
  14. # Case 0: good case: It captures the first inner words.
  15. result0 = re.search(compiled_pattern, line0)
  16.  
  17. print("original 0 : {0}".format(result0.group(0)))
  18. print("expected Head : abc_Head_def_Head")
  19. print("found Head : {0}".format(result0.group(1)))
  20. print("expected Tail : Tail_ghi_Tail_jkl")
  21. print("found Tail : {0}{1}".format(' ' * (result0.regs[2][0]), result0.group(2)))
  22.  
  23. print()
  24.  
  25. # Case 1: Bad case: It captures the last pair words.
  26. result1 = re.search(compiled_pattern, line1)
  27.  
  28. print("original 1 : {0}".format(result1.group(0)))
  29. print("expected Head : abc_Head")
  30. print("found Head : {0}".format(result1.group(1)))
  31. print("expected Tail : Tail_ghi_Head_second_Tail_opq")
  32. print("found Tail : {0}{1}".format(' ' * (result1.regs[2][0]), result1.group(2)))
  33.  
  34. print(testReplaceBetweenWords())
Success #stdin #stdout 0.02s 7032KB
stdin
Standard input is empty
stdout
^((?:(?!Tail).)*Head).*?(Tail.*)$
original 0    : abc_Head_def_Head_inner_inside_Tail_ghi_Tail_jkl
expected Head : abc_Head_def_Head
found Head    : abc_Head_def_Head
expected Tail :                                Tail_ghi_Tail_jkl
found Tail    :                                Tail_ghi_Tail_jkl
()
original 1    : abc_Head_first_Tail_ghi_Head_second_Tail_opq
expected Head : abc_Head
found Head    : abc_Head
expected Tail :                Tail_ghi_Head_second_Tail_opq
found Tail    :                Tail_ghi_Head_second_Tail_opq
None