I'm trying to filter out some objects based on an attribute property in C#. I've decided to do this based on comparing two comma delimited lists such that:
I figure you should be able to do this with a simple regex match expression but I can't figure it out as yet.
Anyone know how to do this? In the mean time going to brute force it with code.
Thanks in advance
--EDIT
by ~ I mean equivalent, sorry for confusion.
also "a,b,c" could also be "abra,barby,candybar". Its not single characters but a list of values.
It's not a regular expression, but it's much simpler than any one could possibly be.
var attributes = input.Split(",");
var testCase = test.Split(",");
return attributes.All(x => testCase.Contains(x)) && testCase.All(x => attributes.Contains(x);
If you find a *, leave off one half of the && expression.
If you want a regex, here's my take on this:
^ # match start of string
(?=.*a(?:,|$)) # assert it matches a followed by a comma or end-of-str
(?=.*b(?:,|$)) # assert it matches b followed by a comma or end-of-str
(?=.*c(?:,|$)) # assert it matches c followed by a comma or end-of-str
(?:(?:a|b|c)(?:,|$))* # match a, b or c followed by a comma or end-of-str
$ # match end of string
In case you find a .*, you keep the assertions but change the last part of the regex to allow it to match anything. Second example:
^ # match start of string
(?=.*a(?:,|$)) # assert it matches a followed by a comma or end-of-str
(?=.*b(?:,|$)) # assert it matches b followed by a comma or end-of-str
(?:[^,]*(,|$))* # match anything followed by a comma or end-of-str
$ # match end of string
Of course you'll still need to parse the string to generate the regex, and at this point I frankly would prefer to just use conventional code (it would probably be faster too), eg (pseudo code):
setRequired = Set(csvRequired.Split(','))
setActual = Set(input.Split(','))
if (setActual.Equals(setRequired)))
{
// passed
}
If you find the asterisk, just remove it from setRequired and use .Contains instead of Equals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With