1

I am trying to match one substring followed by another in a string input at word boundaries using regex. For e.g. if string_1 = "I will give you a call in case I need some help in future"
and if 2 substrings are "will" and "in case I need" it should return true for string 1 but should return false for string below

string_2 = "in case I need some help I will call you" 

I need a case insensitive match and can only use regex.

It should also return false for the below since it does not contain "in case I need" followed by the "will"

string_3 = "I will let you know" 

string_4 = "I will let you know in case we need"

I have looked at Is there a regex to match a string that contains A but does not contain B but unable to determine how I can do look ahead/ look backward for my scenario. That post covers when 2 strings are present without determining if one follows another. Need the solution in python and cant use substring/find etc, so need to be a regex

str = 'I will give you a call in case I need some help in future' 

result = bool(re.search(r'^(?=.*\bwill\b)(?=.*\bin case I need\b).*', str)) 

print(result)

Above matches presence of "will" and "in case I need" without a order. I need order to be enforced and one string to be followed by another i.e. "will" to be followed by "in case I need".

KC.
  • 2,981
  • 2
  • 12
  • 22
K B
  • 19
  • 3

1 Answers1

0

That complicated regexp is only needed because the order doesn't matter. If order matters, it's much simpler:

re.search(r'pattern1.*pattern2', string_to_search)

will look for pattern1 followed by pattern2.

Barmar
  • 741,623
  • 53
  • 500
  • 612