[英]Replace multiple occurrences of a Period in a String in C#
我正在編寫一個代碼,我必須用一次出現替換字符串中多次出現的句點。
我目前正在使用
string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", "\\.");
其中輸入是一個字符串,如 "ABCDEF...GHIJK...LMNOP"
我正在嘗試讓我的輸出為“ABCDEF.GHIJK.LMNOP”,但它不起作用。 我試過了
string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", "");
檢查它是否有效。 事實並非如此。
我怎樣才能做到這一點? 謝謝你的時間!
string input = "one.two..three...four....five";
string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", ".");
Console.WriteLine(output);
Console.Read();
您的問題是您有“ \\”。 作為替換字符串。 它應該只是“。”
嘗試這個:
resultString = Regex.Replace(subjectString, "[.]{2,}", new MatchEvaluator(ComputeReplacement));
它替換兩個或多個.
與一個。
Match the character “.” «[.]{2,}»
Between 2 and unlimited times, as many times as possible, giving back as needed (greedy) «{2,}»
不要使用RegEx :),for-each更容易
StringBuilder sb = new StringBuilder();
char lastChar = '';
foreach (char c in input) {
if (c != '.' || lastChar != '.')
sb.Append(c);
lastChar = c;
}
string result = sb.ToString();
您必須原諒我任何語法錯誤。 在過去的幾個月中,我一直在與Objective-C進行大量合作,並在iPhone上進行輸入。
另一種方法:
var splitted = inputString.Split('.', StringSplitOptions.RemoveEmptyEntries);
var outputString = string.Join('.', splitted);
--
作為一個整潔的襯里:
var outputString = string.Join('.', inputString.Split('.', StringSplitOptions.RemoveEmptyEntries));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.