简体   繁体   English

正则表达式在短语之前检查单词

[英]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. 我正在尝试创建一个正则表达式,如果某些单词在短语之前没有出现,则该表达式仅会返回true。 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. 这是我所能获得的,它不起作用^(?=(^(?:(?!(\\bif\\b)|(\\or\\b)).)\\bstop emailing\\b))会如果我能让它只看6个字以内的字,那也很棒。

Also, if possible I'd also like to check if a question was asked and if so then return false. 另外,如果可能的话,我还要检查是否提出了问题,如果是,则返回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. 我试图添加类似(?!\\?)(^(?:(?!(\\. when\\b)|(\\. what\\b)|(\\. why\\b)|(\\. where\\b)|(\\. how\\b)|(\\. are\\b)).)+$)到上面,但没有成功。

Thank you. 谢谢。

You can use re.match along with conditional operator as mentioned below. 您可以将re.match与条件运算符一起使用,如下所述。

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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