2013-11-26 34 views
1

我正在搜索一個名爲poop的字符串,其中匹配項爲: 「FT」後面跟隨最多6位數字。 FT123456 「FT」後跟任意數量的空格,最多6位數字。例如FT 3435用於在字符串中構建以「FT」開頭的字符串陣列的正則表達式

任何事都可以在比賽後進行,或在比賽開始前進行。 FT123456

這裏是我迄今爲止

string poop = "There must be something to terroir, FT1988 given that expert FT 3245 wine tasters can often identify the region from which a wine comes. But American wine growers have long expressed varying degreesFT26666 of skepticism about this ineffable concept, some dismissing it as unfathomable mysticism and others regarding it as a shrewd >FT34323</a> marketing ploy to protect the cachet of French wines"; 


     Regex regex = new Regex(@"FT\d{1,6}"); 
     Match match = regex.Match(poop); 
     if (match.Success) 
     { 
      return match.Value; 
     } 

     return "tough luck kid"; 

它工作正常,返回爲FT1988的第一場比賽,但不允許空格,而不是建設的所有比賽的數組,這是我真正想要的。

匹配的結果應該是數組{FT1988,FT3245,FT26666,FT34323} 注意,它將刪除它在FT和以下數字之間找到的所有空格。如果它找到兩個相同的值,它不應該添加重複。該數組應該是唯一的值。

在此先感謝!

回答

1

使用FT\s*\d{1,6}和調用Matches()代替Match()

像這樣的東西應該工作:

string poop = "There must be something to terroir, FT1988 given that expert FT 3245 wine tasters can often identify the region from which a wine comes. But American wine growers have long expressed varying degreesFT26666 of skepticism about this ineffable concept, some dismissing it as unfathomable mysticism and others regarding it as a shrewd >FT34323</a> marketing ploy to protect the cachet of French wines"; 

Regex regex = new Regex(@"FT\s*\d{1,6}"); 
var retVal = new List<string>(); 
foreach (Match match in regex.Matches(poop)) 
    retVal.Add(match.Value.Replace(" ", "")); 

return retVal.Distinct().ToList(); 

仔細考慮您的要求。如果在「FT」字符串之前或之後有任何內容,那麼正則表達式也將匹配「1234567890FT1234567890」中的「FT123456」。這可能是你所期望的或不是。

+0

return retVal.Distinct()。ToList()是必需的,否則像魅力一樣工作。謝謝! – user2580209

+0

好抓!我實際上無法測試它。我會更新後代。 – acfrancis

0

考慮下面的正則表達式...

^FT[\s\d]{1,6}$ 

祝您好運!

相關問題