简体   繁体   English

使用正则表达式在文本中的任意位置找到两个单词

[英]Finding two words anywhere in text with regular expression

I'm not an expert at regular expressions by any stretch of the imagination! 凭空想像力,我不是正则表达式方面的专家! I understand the basics of how regex comes together, but through a regular expression, can I search for two words that could appear anywhere within a piece of text? 我了解正则表达式如何组合在一起的基础知识,但是通过正则表达式,我可以搜索可能出现在一段文本中任何地方的两个单词吗?
ie the words hot and weather. 即炎热和天气。 Could be written as: the weather was hot during the hot weather the weather has become even hotter 可以这样写:天气炎热,天气炎热,天气变得更热

Is it possible that a regex can be created to pick up all three scenarios, but not (for example) the picture was shot in poor weather? 是否可以创建一个正则表达式来拾取所有三种情况,但是(例如)图片不是在恶劣的天气下拍摄的?

Any help would be appreciated - I'm working in PHP5.6 by the way alternative is there a better way to do it that I haven't thought of? 任何帮助将不胜感激-我正在使用PHP5.6进行替代,是否有没有想到的更好的方法?

If you just need those two words you could have the regex search with an optional list of word endings. 如果只需要这两个单词,则可以进行正则表达式搜索,并带有可选的单词结尾列表。

For Example: (\\bweather\\b.*hot(ter|test)?\\b|\\bhot(ter|test)?\\b.*\\bweather\\b) 例如: (\\bweather\\b.*hot(ter|test)?\\b|\\bhot(ter|test)?\\b.*\\bweather\\b)

But if you need to build the regex from a user's input you would want to have a full list of possible endings: (s|er|est|ier|iest|ter|test|etc|etc)? 但是,如果您需要根据用户输入来构建正则表达式,则需要完整的可能结尾列表: (s|er|est|ier|iest|ter|test|etc|etc)?

Example: (\\bweather(s|er|est|ier|iest|ter|test|etc|etc)?\\b.*hot(s|er|est|ier|iest|ter|test|etc|etc)?\\b|\\b(s|er|est|ier|iest|ter|test|etc|etc)?\\b.*\\bweather(s|er|est|ier|iest|ter|test|etc|etc)?\\b) 例如: (\\bweather(s|er|est|ier|iest|ter|test|etc|etc)?\\b.*hot(s|er|est|ier|iest|ter|test|etc|etc)?\\b|\\b(s|er|est|ier|iest|ter|test|etc|etc)?\\b.*\\bweather(s|er|est|ier|iest|ter|test|etc|etc)?\\b)

The only problem is it would miss endings like silly being silliest or see being saw without adding additional logic to look at the original words. 唯一的问题是,如果没有添加其他逻辑来查看原始单词,就会错过像sillysilliest那样的结尾或see别人saw结尾。

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

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