2015-11-18 46 views
0

比方說,我有一個文本:如何在文本行中逐一編輯特定的單詞?

「他的名字是傑克·傑克很喜歡騎自行車。」

什麼方法,你會建議使用編輯字「傑克」一個接一個,比如我希望對每個「傑克」進行特定的更改。我試過使用Remove()和Replace(),但是這些方法在文本中編輯所有「Jack」。

+0

可能重複http://stackoverflow.com/questions/8809354/replace-first-occurrence-of-pattern-in-a-string –

回答

2

Regex.Replace(String, MatchEvaluator)可能是你需要的。在指定的輸入字符串中,它將使用由MatchEvaluator委託人返回的字符串替換與指定正則表達式匹配的所有字符串。
因此,您的MatchEvaluator代表可以決定用什麼來替換每一個「傑克」。
例如:

string s = "His name is Jack. Jack likes to ride a bike"; 
int count = 0; 
string s2 = Regex.Replace(s, "Jack", match => { 
    count++; 
    return count > 1 ? "Jack2" : "Jack1"; 
}); 

s2爲:

他的名字是Jack1。 Jack2喜歡騎自行車

+0

感謝,這正是我需要的 – Redas

相關問題