简体   繁体   English

检查与正则表达式匹配的多个单词

[英]Check multiple words match with Regex

I'm looking for a RegExp that checks if 2 or more words are present in a string regardless of their order.我正在寻找一个 RegExp 来检查字符串中是否存在 2 个或更多单词,而不管它们的顺序如何。

If I want to find the words "dog" and "cat", the expression must find a match only when they are both in the sentence:如果我想找到“dog”和“cat”这两个词,表达式必须只有在它们都在句子中时才能找到匹配项:
"I like dogs" - no match “我喜欢狗”——不匹配
"I love cats" - no match “我爱猫”——不匹配
"I own a dog and a cat" - ok “我有一只狗和一只猫”——好的

The regular expression pattern in this example will match both "dog" and "cat" in a sentence.此示例中的正则表达式模式将匹配句子中的“dog”和“cat”。 It does this by using alternation with the |它通过使用|的交替来做到这一点operator, which allows either "dog" or "cat" to appear in the first and second positions.运算符,它允许“狗”或“猫”出现在第一个和第二个位置。 This means that the pattern will match sentences such as "I own a dog and a cat" and "I own a cat and a dog".这意味着该模式将匹配诸如“I own a dog and a cat”和“I own a cat and a dog”之类的句子。

Demo: https://dotnetfiddle.net/pU2HhD演示: https ://dotnetfiddle.net/pU2HhD

Implementation:执行:

public class Program
{
    public static void Main()
    {
        List<string> sentences = new List<string>
        {
            "I like dogs",
            "I love cats",
            "I own a dog and a cat",
            "I own a cat and a dog"
        };
        
        string pattern = @"\b(dog|cat)\b.*\b(dog|cat)\b";
        
        foreach (var sentence in sentences) 
        {
            Match match = Regex.Match(sentence, pattern);
            if (match.Success)
                Console.WriteLine($"{sentence} - ok");
            else
                Console.WriteLine($"{sentence} - no match");
        }
    }
}

Output:输出:

I like dogs - no match
I love cats - no match
I own a dog and a cat - ok
I own a cat and a dog - ok
^.*(dog).*(cat)|.*(cat).*(dog).*$

this should do the trick.这应该可以解决问题。

.*(dog).*(cat) the first part checks if the string contains "dog" before "cat" .*(dog).*(cat)第一部分检查字符串是否在“cat”之前包含“dog”

.*(cat).*(dog).* the second part checks if the string contains "cat" before "dog" .*(cat).*(dog).*第二部分检查字符串是否在“dog”之前包含“cat”

| is a logic operator for OR是 OR 的逻辑运算符

^ and $ are anchors and match the start and the end ^$是锚点,匹配开始和结束

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

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