我正在尝试根据C#中的属性属性过滤掉一些对象。我决定在比较两个逗号分隔的列表时这样做:
我认为你应该可以用一个简单的正则表达式匹配表达式做到这一点,但我还不能解决它。
任何人都知道如何做到这一点?同时用代码来强制它。
提前致谢
- 编辑
通过〜我的意思相当,抱歉混淆。
也“a,b,c”也可能是“abra,barby,candybar”。它不是单个字符,而是一系列值。
答案 0 :(得分:4)
这不是正则表达式,但它比任何人都简单得多。
var attributes = input.Split(",");
var testCase = test.Split(",");
return attributes.All(x => testCase.Contains(x)) && testCase.All(x => attributes.Contains(x);
如果找到*,请忽略&&
表达式的一半。
答案 1 :(得分:2)
如果你想要一个正则表达式,这里是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
如果您找到.*
,则保留断言,但更改正则表达式的最后一部分以允许它匹配任何内容。 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
当然你仍然需要解析字符串以生成正则表达式,此时我坦率地更喜欢使用传统代码(它可能会更快),例如(伪代码):
setRequired = Set(csvRequired.Split(','))
setActual = Set(input.Split(','))
if (setActual.Equals(setRequired)))
{
// passed
}
如果您找到星号,只需将其从setRequired
移除,然后使用.Contains
代替Equals
答案 2 :(得分:-2)
尝试
((a|b|c)(,|))+
其中a,b和c是列表中的每个选项。 Here's perma链接到我在regexpal中的快速测试。如果你看一下最后一个测试“a,x,b”,正则表达式匹配两个独立的部分,但我认为它仍然可以在C#中使用Regex.Match()