我有一個字符串,有2個相似的單詞..我想代替2秒的第二個單詞,但不是第一個..任何幫助?取代第二場比賽跳過第一場比賽在C#
1
A
回答
1
您可以使用正則表達式和逆序。
var replaceHello = "ABC hello 123 hello 456 hello 789";
var fixedUp = Regex.Replace(replaceHello, "(?<=hello.*)hello", "goodbye");
這將用「再見」替換「再見」這個詞的所有例子,除了第一個例外。
+0
+1的解決方案。它是有益的。謝謝 – 2011-04-27 04:19:15
0
Regex
版本簡潔,但如果您不是那種使用正則表達式的人,則可以考慮更多的代碼。
StringBuilder
類提供了一種在給定子字符串內進行替換的方法。在string
的擴展方法中,我們將指定一個從第一個適用匹配結束時開始的子字符串。針對論據的一些基本驗證已到位,但我不能說我已經測試過所有組合。
public static string SkipReplace(this string input, string oldValue, string newValue)
{
if (input == null)
throw new ArgumentNullException("input");
if (string.IsNullOrEmpty(oldValue))
throw new ArgumentException("oldValue");
if (newValue == null)
throw new ArgumentNullException("newValue");
int index = input.IndexOf(oldValue);
if (index > -1)
{
int startingPoint = index + oldValue.Length;
int count = input.Length - startingPoint;
StringBuilder builder = new StringBuilder(input);
builder.Replace(oldValue, newValue, startingPoint, count);
return builder.ToString();
}
return input;
}
使用它:
string foobar = "foofoo".SkipReplace("foo", "bar");
相關問題
- 1. 如何第一場比賽
- 2. GROK第三場比賽
- 3. 不包括第一場比賽,BeautifulSoup
- 4. 比賽第一場,然後加入行
- 5. 贏得第3場比賽的條件
- 6. 正則表達式的幫助 - 提取的第二場比賽
- 7. 搜索字符串並抓取第二場比賽
- 8. 其中第二場比賽的一些標準只打印線
- 9. SED替代(錯誤地)停在第一場比賽
- 10. 爲每場比賽
- 11. 我需要匹配一個正斜槓的URL,但跳過第一場比賽
- 12. 忽略第二場比賽中的HTML如果不匹配
- 13. 正則表達式與第二場比賽的JavaScript
- 14. Qt正則表達式從第一場比賽開始到最後一場比賽結束
- 15. 讓這個Javascript函數只能運行在第一場比賽
- 16. SAS:僅在第一場比賽中合併
- 17. jQuery的返回的第一場比賽在選擇列表
- 18. Javascript lookbehind在第一場比賽中停止
- 19. 正則表達式停在第一場比賽
- 20. 如何讓grep在第一場比賽中停下來?
- 21. Perl遍歷每場比賽
- 22. XNA聯兩場比賽
- 23. 正則表達式 - 想要兩場比賽只獲得一場比賽
- 24. 正則表達式站第一場比賽
- 25. 的sed插入上的第一場比賽只
- 26. 我的第一場比賽:Python使用pygame與Java使用lwjgl?
- 27. PHP preg_match_all沒有找到第一場比賽
- 28. 如何使用DirectoryInfo.GetFiles並找到第一場比賽後停止?
- 29. Android Espresso執行點擊第一場比賽
- 30. 去除括號替換第一場比賽
着」你/沒有幫助的例子更多細節 – BrokenGlass 2011-04-27 03:54:36