如何在文本行中一个一个地编辑特定单词?
How can I edit particular word one by one in a text line?
假设我有一条短信:
"His name is Jack. Jack likes to ride a bike"
你建议用什么方法逐个编辑单词"Jack",比如我想对每个"Jack"做具体修改。我试过使用 Remove() 和 Replace(),但这些方法会编辑文本中的所有 "Jack"。
Regex.Replace(String, MatchEvaluator) may be what you need. In the specified input string, it replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator 代表。
因此,您的 MatchEvaluator 代表可以决定将每个 "Jack" 替换为什么。
例如:
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 是:
His name is Jack1. Jack2 likes to ride a bike
假设我有一条短信:
"His name is Jack. Jack likes to ride a bike"
你建议用什么方法逐个编辑单词"Jack",比如我想对每个"Jack"做具体修改。我试过使用 Remove() 和 Replace(),但这些方法会编辑文本中的所有 "Jack"。
Regex.Replace(String, MatchEvaluator) may be what you need. In the specified input string, it replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator 代表。
因此,您的 MatchEvaluator 代表可以决定将每个 "Jack" 替换为什么。
例如:
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 是:
His name is Jack1. Jack2 likes to ride a bike