C# 替换一个单词,但仅在特定行上替换
在我的应用程序中,我必须替换出现在一行以上的文本中的一些单词C# 替换一个单词,但仅在特定行上替换,c#,asp.net,regex,C#,Asp.net,Regex,在我的应用程序中,我必须替换出现在一行以上的文本中的一些单词 Most at-home desensitizing toothpastes work by primarily numbing the nerve and masking the pain Traditional potassium iron-based toothpastes in the form of potassium nitrate, potassium citrate. 我想将第三行中的“钾”仅替换为“”,我的代码是
Most at-home desensitizing toothpastes work by
primarily numbing the nerve and masking the pain
Traditional potassium iron-based toothpastes in the
form of potassium nitrate, potassium citrate.
我想将第三行中的“钾”仅替换为“”,我的代码是
string text = t.Replace("potassium", "");
问题是所有行中的单词都被删除了
如何替换特定行段落中的任何一个单词?让我们先看看正则表达式()。然后可以通过编程方式更改参数 此正则表达式针对第三行上的第一个
k
:
(?<=\A(?:[^\r\n]*\r?\n+){2}[^\r\n]*?)potassium
要替换第三行上的所有钾,我们使用\G
:
(?<=\A([^\r\n]*\r?\n+){2}[^\r\n]*?|\G[^\r\n]*?)potassium
解释
(?让我们先看看regex()。然后可以通过编程更改参数 此正则表达式针对第三行上的第一个
:k
要替换第三行上的所有钾,我们使用(?<=\A(?:[^\r\n]*\r?\n+){2}[^\r\n]*?)potassium
:\G
解释(?<=\A([^\r\n]*\r?\n+){2}[^\r\n]*?|\G[^\r\n]*?)potassium
(?最简单但不是最好的:
var multiLineString = "Most at-home desensitizing toothpastes work by" + Environment.NewLine + "primarily numbing the nerve and masking the pain" + Environment.NewLine + "Traditional potassium iron-based toothpastes in the" + Environment.NewLine + "form of potassium nitrate, potassium citrate."; var lines = multiLineString .Split(Environment.NewLine); lines[lines.Length-1] = lines[lines.Length-1].Replace("potassium ", ""); var resultingLine = String.Join(lines, Environment.NewLine))
最简单但不是最好的:var multiLineString = "Most at-home desensitizing toothpastes work by" + Environment.NewLine + "primarily numbing the nerve and masking the pain" + Environment.NewLine + "Traditional potassium iron-based toothpastes in the" + Environment.NewLine + "form of potassium nitrate, potassium citrate."; var lines = multiLineString .Split(Environment.NewLine); lines[lines.Length-1] = lines[lines.Length-1].Replace("potassium ", ""); var resultingLine = String.Join(lines, Environment.NewLine))
下面的正则表达式将与第三行中出现的字符串pottassium匹配
你的代码是potassium(?!\s*\w+[.,])
replaced = Regex.Replace(yourString, @"potassium(?!\s*\w+[.,])", "");
下面的正则表达式将与第三行中出现的字符串pottassium匹配
你的代码是potassium(?!\s*\w+[.,])
replaced = Regex.Replace(yourString, @"potassium(?!\s*\w+[.,])", "");
您是否将行存储在一个字符串中?为什么不希望删除第四行中的pottassium?因为由于API的输出,只有该单词被错误放置。字符串是否有任何换行符来标识新行?如果有,您可以按换行符拆分,然后替换特定行中的特定单词。您是否将行存储在一个字符串中ing?为什么不希望删除第四行中的pottassium?因为由于API的输出,只有该单词被错误地放置。字符串是否有任何换行符来标识新行?如果有,可以按换行符拆分,然后替换特定行中的特定单词。为什么不更简单的
?是的,我只是认为钾也在其他行中。可能是,但他说他只想在第三行中替换,而不是相反。现在这无关紧要。但我会纠正它。谢谢。为什么不更简单一点行[2]。替换(…)
?是的,我只是认为钾也在其他行中。可能是,但他说他只想在第三行中替换,而不是相反。现在这无关紧要。但我会纠正它。谢谢。谢谢,很高兴它能起作用!仅供参考,添加了解释和变体,以替换第3行中的所有行[2]。替换(…)
钾的实例,而不仅仅是第一个。小演示以防万一。:)谢谢,很高兴它能工作!仅供参考,添加了解释和一个变体,以替换第3行的所有
,而不仅仅是第一个。小演示以防万一。:)k