2017-02-02 48 views
1

我的要求如下:如何刪除字符串中的某些字符發生後的子字符串?

input => "Employee.Addresses[].Address.City" 
output => "Empolyee.Addresses[].City" 
(Address is removed which is present after [].) 

input => "Employee.Addresses[].Address.Lanes[].Lane.Name" 
output => "Employee.Addresses[].Lanes[].Name" 
(Address is removed which is present after []. and Lane is removed which is present after [].) 

如何做到這一點在C#中?

+1

什麼是 「立竿見影」?多個括號會發生什麼?問題根本不清楚 – trailmax

回答

1
private static IEnumerable<string> Filter(string input) 
{ 
    var subWords = input.Split('.'); 
    bool skip = false; 

    foreach (var word in subWords) 
    { 
     if (skip) 
     { 
      skip = false; 
     } 
     else 
     { 
      yield return word; 
     } 

     if (word.EndsWith("[]")) 
     { 
      skip = true; 
     } 
    } 
} 

現在你使用這樣的:

var filtered = string.Join(".", Filter(input)); 
0

此功能的[]支架對後立即修剪出任何段。

public static String trimPostBrackets(string s){ 
     List<String> sp = new List<String>(s.Split('.')); //Separate it by segment 
     for(int i=0;i<sp.Count;i++)      //For each segment... 
      if(sp[i].EndsWith("[]") && i+1 < sp.Count) //If it ends with "[]" and there's a following segment... 
       sp.RemoveAt(i+1);       //Remove the following segment 
     return String.Join(".",sp);      //Put the surviving segments back together and return them 
    } 
1

正則表達式如何?

Regex rgx = new Regex(@"(?<=\[\])\..+?(?=\.)"); 
string output = rgx.Replace(input, String.Empty); 

說明:

(?<=\[\])   //positive lookbehind for the brackets 
     \.   //match literal period 
      .+?  //match any character at least once, but as few times as possible 
       (?=\.) //positive lookahead for a literal period 
+1

這個工作,但斜線需要逃脫,所以你得到這樣的東西:'正則表達式rgx =新的正則表達式(「(?<= \\ [\\])\\ .. *?( ?= \\。)「);' – awh112

+1

該字符串被標記爲逐字字符串文字,斜槓很好 – ColinM

+2

@ColinM其實並不在他評論時。 – Setsu

0

你的需要所缺乏的描述。如果我不正確地理解它,請糾正我。

你需要找到的模式"[].",然後這個模式之後刪除一切,直到下一個點.

如果是這樣的話,我相信使用正則表達式可以很容易地解決這個問題。

因此,模式"[]."可以寫在正則表達式作爲 "\[\]\."

然後,你需要這個模式,直到下一個點後,發現一切:".*?\."(該.*?意味着每個字符多次可能的,但以非貪婪的方式,即停在找到的第一個點上)。

所以,整個模式將是:

var regexPattern = @"\[\]\..*?\."; 

而且你要替換此模式的所有匹配「[]」。 (即刪除括號後面的內容直到點)。

所以你調用Replace方法在Regex類:

var result = Regex.Replace(input, regexPattern, "[]."); 
相關問題