2012-10-24 79 views
3

我想根據C#中的屬性屬性過濾掉一些對象。我已經決定基於比較兩個逗號分隔的列表,例如,要做到這一點:正則表達式比較?

  • 「A,B,C」 〜 「A,B,C」, 「A,C,B」,「C, A,b」等。
  • 「A,b,*」 〜 「A,b,C」, 「A,d,b」, 「G,A,b」, 「A,b」,等..
  • 「A,b,C」!〜 「A,C,d」, 「A,C」, 「A」,等等。

我想你應該能夠做到這一點用一個簡單的正則表達式匹配表達式,但我還沒弄明白。

任何人都知道如何做到這一點?同時要用代碼蠻力。

在此先感謝

--edit

靠〜我的意思是等價的,遺憾的混亂。

也是 「A,B,C」 也可以 「阿布拉,巴比,直板」。它不是單個字符,而是一個值列表。

+9

我寧願爲此編寫正常的代碼...我知道這是完全可以強制正則表達式的解決方案,但我寧願不去那裏。 – nhahtdh

+0

'〜'是什麼。我無法理解你想做什麼...... – Anirudha

+0

@ Fake.It.Til.U.Make.It:可能是排列組合。 – nhahtdh

回答

4

這不是一個正則表達式,但它比任何人都可能更簡單。

var attributes = input.Split(","); 
var testCase = test.Split(","); 

return attributes.All(x => testCase.Contains(x)) && testCase.All(x => attributes.Contains(x); 

如果您發現*,請放棄&&表達式的一半。

+0

嗯...很好的解決方案 – Anirudha

+0

呀,那是少做的工作。我變成了'... &&(attributes.Any(x => x ==「*」)|| textCase.All(x => attributes.Contains(x)))' – danatcofo

+0

@ Fake.It.Til。 U.Make.It - 謝謝:) – Bobson

-2

嘗試 ((a|b|c)(,|))+

其中a,b和c是列表中的每個選項。 Here's perma鏈接到我的快速測試正則表達式。如果你看一下上次測試「A,X,B」的正則表達式匹配的是兩個獨立的部分,但我認爲它會在C#中使用Regex.Match()

+0

我可以得到aaaaaaaaaaaaaaaaaaaaaaaa來匹配你的正則表達式。 – nhahtdh

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

+0

[alternate first](http://rubular.com/r/ieLdBFMxx9)用單詞與字母測試第一個場景的結果。像魅力一樣工作! – danatcofo

+0

我正在考慮它可能更少的計算蠻力比較...正則表達式可能會變得昂貴。 – danatcofo

+0

@danatcofo正則表達式沒有任何魔法,它仍然必須去找到所有這些字符串。傳統代碼更可能會更快。我更多地寫了正則表達式來看看我是否可以。 – NullUserException