Home > Software design >  Python regex stop matching after string
Python regex stop matching after string

Time:11-04

I am currently trying to match the following cases, which works most of the time, but I'll explain the exception in a second:

  • someword.something.lis
  • something.lis

However, matches are also made for the case: something.lis.some.bad.values.here.after.the.string

My current regex is:

f". {user_input_string}|{user_input_string}"

however, I need to regex matching to stop kind of like (lets say and exclamation mark is a stop symbol):

f". {user_input_string}!|{user_input_string}!"

CodePudding user response:

I think you want a positive lookahead assuming you don't wish to capture the stop symbol:

f". {user_input_string}(?=!)|{user_input_string}(?=!)"

Tangentially, . makes no sense. You could simplify it to:

f".*{user_input_string}(?=!)"
  • Related