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
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
Let's say I have following items:
I like to get all lines / items with "Hello" except this lines where is a "Mary" or "Paul".
So my desired outcome would be:
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:
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