Regex for a search with exceptions

Frank Mehlhop 96 Reputation points
2021-10-29T13:46:31.917+00:00

I'm looking for a regex expression in .Net environment.
I want to get all items including "Hello",
but not when on the same item is also "Paul" or "Mary".

How does it look like?

Frank

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,080 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Frank Mehlhop 96 Reputation points
    2021-11-01T06:48:01.307+00:00

    Let's say I have following items:

    • Hello Joe
    • Hello Mary
    • Hello Bill
    • How are you
    • It's a nice day

    I like to get all lines / items with "Hello" except this lines where is a "Mary" or "Paul".
    So my desired outcome would be:

    • Hello Joe
    • Hello Bill
    0 comments No comments

  2. Zhi Lv - MSFT 31,946 Reputation points Microsoft Vendor
    2021-11-02T09:03:26.107+00:00

    Hi @Frank Mehlhop ,

    I assume you are using a string list to store the items, if that is the case, you could refer the following sample code:

            List<string> stritems = new List<string>()  
            {  
                "Hello Joe",  
                "Hello Mary",  
                "Hello Bill",  
                "How are you",  
                "It's a nice day",  
            };  
            //filter the items start with Hello  
            Regex rx = new Regex(@"\bHello\s+(\w+?)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);  
    
            //filter the item with Hello Mary and Hello Paul.  
            Regex rx2 = new Regex(@"\bHello\s+(Mary)|(Paul)\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);  
    
            //used to store the result.  
            List<string> result = new List<string>();  
    
            //loop through the items and filter data.  
            foreach(var item in stritems)  
            {  
                if (rx.IsMatch(item) && !rx2.IsMatch(item))  
                {  
                    result.Add(item);//add the matched items to the result.  
                }  
    
            }  
    
            //another method: Using Linq query statement https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/  
            var namelist = new List<string>() { "Mary", "Paul" };   
            var result2 = stritems.Where(c => c.StartsWith("Hello") && !namelist.Any(d => c.Contains(d))).ToList();  
    

    The result as below:

    145746-2.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments