2017-08-01 59 views
0

字符串開始我有一個字符串,它看起來像這樣替換字符串,如果在列表

s = "<Hello it´s me, <Hi how are you <hay" 

和列表 List<string> ValidList= {Hello, hay}我需要的結果字符串要像

string result = "<Hello it´s me, ?Hi how are you <hay" 

這樣結果字符串如果它開始於<,其餘的信號到列表中,保留它,否則,如果以<開頭,但不是列表中的H替代H?

我嘗試使用的IndexOf找到<的位置,如果字符串後starsWith列表中的任何字符串的離開它。

foreach (var vl in ValidList) 
{ 
    int nextLt = 0; 
    while ((nextLt = strAux.IndexOf('<', nextLt)) != -1) 
    { 

     //is element, leave it 
     if (!(strAux.Substring(nextLt + 1).StartsWith(vl))) 
     { 
      //its not, replace 
      strAux = string.Format(@"{0}?{1}", strAux.Substring(0, nextLt), strAux.Substring(nextLt + 1, strAux.Length - (nextLt + 1))); 
     } 
     nextLt++; 
    } 
} 
+4

'Regex.Replace(S,的String.Format( 「<({0})?!」 的string.join( 「|」,ValidList) ),「?」)' – poke

+0

但是在有這個字符串的情況下s =「<你好,它是我的

+1

你根本沒有指定什麼應該發生在不是一個詞的前綴的<<處。你也沒有舉一個例子。你也沒有提到我能想到的所有其他邊緣案例。 – poke

回答

1

爲了讓我給一個評論它應有的答案解決方案:

Regex.Replace(s, string.Format("<(?!{0})", string.Join("|", ValidList)), "?") 

這個(顯然)使用正則表達式的?更換不需要<字符。爲了識別這些字符,我們使用a negative lookahead表達式。對於示例單詞列表,這看起來像這樣:(?!Hallo|hay)。這隻有在我們所匹配的產品沒有跟隨Hallohay時纔會匹配。在這種情況下,我們匹配<,因此完整表達式變成<(?!Hallo|hay)

現在我們只需要通過創建正則表達式來動態地解釋動態ValidList。那裏我們使用string.Formatstring.Join

0

使用LINQ.It一種可能的解決分裂使用<並檢查「字」以下(文本,直到找到一個空的空間)是在有效列表,加入<?相應的字符串。最後,它加入了一切:

List<string> ValidList = new List<string>{ "Hello", "hay" }; 
string str = "<Hello it´s me, <Hi how are you <hay"; 

var res = String.Join("",str.Split(new char[] { '<' }, StringSplitOptions.RemoveEmptyEntries) 
       .Select(x => ValidList.Contains(x.Split(' ').First()) ? "<" + x : "?"+x)); 
0

像這樣的事情,而無需使用正則表達式或LINQ

 string s = "<Hello it´s me, <Hi how are you <hay"; 
     List<string> ValidList = new List<string>() { "Hello", "hay" }; 

     var arr = s.Split(new[] { '<' }, StringSplitOptions.RemoveEmptyEntries); 
     for (int i = 0; i < arr.Length; i++) 
     { 
      bool flag = false; 
      foreach (var item in ValidList) 
      { 
       if (arr[i].Contains(item)) 
       { 
        flag = false; 
        break; 
       } 
       else 
       { 
        flag = (flag) ? flag : !flag; 
       } 
      } 

      if (flag) 
       arr[i] = "?" + arr[i]; 
      else 
       arr[i] = "<" + arr[i]; 
     } 

     Console.WriteLine(string.Concat(arr));