简体   繁体   中英

Regex to check for words before phrase

I'm trying to create a regex that will only return true if certain words don't show up before a phrase. For example, I want it to return True for this sentence "stop emailing me" and false for "Message me if you have that in stock. If not, stop emailing me". This is as close as I could get and it doesn't work ^(?=(^(?:(?!(\\bif\\b)|(\\or\\b)).)\\bstop emailing\\b)) Would also be great if I could keep it to looking just at words within 6 words or so.

Also, if possible I'd also like to check if a question was asked and if so then return false. I was trying to add something like (?!\\?) and (^(?:(?!(\\. when\\b)|(\\. what\\b)|(\\. why\\b)|(\\. where\\b)|(\\. how\\b)|(\\. are\\b)).)+$) to the above but no success.

Thank you.

You can use re.match along with conditional operator as mentioned below.

pattern = "stop\s+emailing\s+me"
result = True if re.match(pattern,content,re.M) else False

Another alternate solution is split the string as ,

string = "stop emailing me"
list = string.split()
True if list[0] = 'stop' and list[1] = 'emailing' and list[2] = 'me' else False  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM