2016-10-05 44 views
4

我需要插入一個特定符號之前和之後(單)空格(如「|」),像這樣:插入(單)空格前的特定符號,之後

string input = "|ABC|xyz |123||999| aaa| |BBB"; 
string output = "| ABC | xyz | 123 | | 999 | aaa | | BBB"; 

這可以很容易地實現使用一些正則表達式模式:

string input = "|ABC|xyz |123||999| aaa| |BBB"; 

// add space before | 
string pattern = "[a-zA-Z0-9\\s*]*\\|"; 
string replacement = "$0 "; 
string output = Regex.Replace(input, pattern, replacement); 

// add space after | 
pattern = "\\|[a-zA-Z0-9\\s*]*"; 
replacement = " $0"; 
output = Regex.Replace(output, pattern, replacement); 

// trim redundant spaces 
pattern = "\\s+"; 
replacement = " "; 
output = Regex.Replace(output, pattern, replacement).Trim(); 

Console.WriteLine("Original String: \"{0}\"", input); 
Console.WriteLine("Replacement String: \"{0}\"", output); 

但這不是我想要的,我的目標只是使用單一模式。

我嘗試了很多方法,但仍然無法按預期工作。請有人幫我解決這個問題。

非常感謝你提前!

+0

定義「不按預期工作」。你沒有得到任何回報?錯誤的結果?一個錯誤? – Tim

+0

沒有錯誤,但錯誤的輸出結果,例如有更多的空間比必要的(而不是1空間),這就是爲什麼我想要組合一些模式,但是有可能使用一個模式來實現這一點? –

回答

1

試試這個。

string input = "|ABC|xyz |123||999| aaa| |BBB"; 

string pattern = @"[\s]*[|][\s]*"; 
string replacement = " | "; 
string output = Regex.Replace(input, pattern, replacement); 
+0

謝謝,但''|'''之間仍有多餘的空格,輸出是'「| ABC | xyz | 123 | | 999 | aaa | | BBB」'。如果沒有解決方案,也許我必須使用一種模式來消除多餘的空白。 –

+0

@PhongHo我認爲你可以使用他的正則表達式來獲得你的結果。我們只是寫更多的正則表達式C#代碼:)。 –

0

嘗試這種解決方案的基礎上,this answer

var str = "|ABC|xyz |123||999| aaa| |BBB"; 
var fixed = Regex.Replace(str, patt, m => 
      { 
       if(string.IsNullOrWhiteSpace(m.Value))//multple spaces 
        return ""; 
       return " | "; 
      }); 

這將返回| ABC | xyz | 123 | | 999 | aaa | | BBB

我們都還是老樣子由於與|更換|BBB|(space)(space)|之間aaa但這是。

4

謝謝@Santhosh Nayak。

我只是寫更多的C#代碼來獲得輸出作爲OP想要的。

string input = "|ABC|xyz |123||999| aaa| |BBB"; 
string pattern = @"[\s]*[|][\s]*"; 
string replacement = " | "; 
string output = Regex.Replace(input, pattern, (match) => { 
    if(match.Index != 0) 
     return replacement; 
    else 
     return value; 
}); 

我在MSDN中提到Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

相關問題