2012-03-24 110 views
0

我想匹配兩個串彼此,而不在意三個條件:定義字符忽略同時匹配字符串C#

1-區分大小寫(都應該不區分大小寫):誰< =>誰

2-下劃線:father_of < =>的父

3缺失空間:barackobama < =>布魯克斯

因此,下面兩個字符串應當彼此匹配

誰是fatherof barack_obama < =>誰是奧巴馬的父親

我不知道從哪裏開始,我試圖讓兩個字符串的排列,考慮下劃線和缺少空格的這兩種情況下,所以它會像

Who, is, fatherof, barack_obama 

who is, is fatherof, fatherof barack_obama, 
whois, isfatherof, fatherofbarack_obama, 
who_is, is_fatherof, fatherof_barack_obama, 

who is fatherof, is fatherof barack_obama 
whoisfatherof, isfatherofbarack_obama 
who_is_fatherof, is_fatherof_barack_obama 

who is fatherof barack_obama 
whoisfatherofbarack_obama 
who_is_fatherof_barack_obama 

這是很好的匹配奧巴馬與barack_obama但反過來並不好,即使我能夠在兩者之間有undserscore分割字符串,我不能做到這一點與失蹤空間

+3

您預期提出問題,而不是分配任務。 – 2012-03-24 20:24:37

+1

@HansPassant你會得到'我該怎麼做?') – 2012-03-24 20:26:19

+1

嗯,這是一個合理的猜測,我猜。我猜不出爲什麼我們必須猜測。 – 2012-03-24 20:30:22

回答

6

也許會:

public static class StringExtensions 
{ 
    private string NormalizeText(string text) 
    { 
    return text..Replace("_","") 
       .Replace(" ","") 
       .Replace(",",""); 

    } 

    public static bool CustomEquals(this string instance, string otherString) 
    { 
    return NormalizeText(instance).Equals(NormalizeText(otherString), 
              StringComparison.CurrentCultureIgnoreCase); 
    } 
} 

所以

"Who is the fatherof barack_obama" 
"who IS the father of barack obama" 

比較喜歡(忽略大小寫)

"Whoisthefatherofbarackobama" 
"whoISthefatherofbarackobama" 
+0

是的,這可能比利用正則表達式更可讀。 +1 – dwerner 2012-03-24 20:30:07

+0

更新爲使用OP(逗號)添加的新條件進行匹配。 – 2012-03-24 20:31:46

+1

功能在stackoverflow蠕變。我一直注意到這種趨勢。問得很快,修改爲答案開始進來。它是有道理的,使一個問題更好 - 但這種家庭作業PLZ GIMME代碼的東西... – dwerner 2012-03-24 20:35:26

2

短一點的版本與用於去除字符的正則表達式:

public static class StringExtensions 
{ 
    public static bool CustomEquals(this string current, string other) 
    { 
     string pattern = @"[_\s,]"; 
     return String.Equals(
      Regex.Replace(current, pattern, String.Empty), 
      Regex.Replace(other, pattern, String.Empty), 
      StringComparison.CurrentCultureIgnoreCase); 
    } 
}