替换单词,但仅限于特定行

时间:2014-06-27 05:41:23

标签: 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.

我想用“”替换第3行中的“钾”。我的代码是

string text = t.Replace("potassium", "");

问题是该单词已从所有行中删除。

如何从特定行的段落中替换任何一个单词?

3 个答案:

答案 0 :(得分:2)

让我们先看一下正则表达式(demo here)。然后,您可以以编程方式更改参数。

此正则表达式定位第三行的第一个potassium

(?<=\A(?:[^\r\n]*\r?\n+){2}[^\r\n]*?)potassium

将其替换为bromide

replaced = Regex.Replace(yourString, @"(?<=\A(?:[^\r\n]*\r?\n+){2}[^\r\n]*?)potassium", "bromide");

要替换第三行的所有potassium,我们使用\G

(?<=\A([^\r\n]*\r?\n+){2}[^\r\n]*?|\G[^\r\n]*?)potassium

使用参数:替换任意行上的任何字

要替换someword行上的单词n,请以编程方式构建正则表达式字符串。在正则表达式中,您必须使用n-1,因为这是我们跳过的行数。

var myRegex = new Regex(@"(?<=\A(?:[^\r\n]*\r?\n+){" + (n-1) + @"}[^\r\n]*?)" + someword );

<强>解释

  • (?<=\A([^\r\n]*\r?\n+){2}[^\r\n]*?)是一个很大的观察者,断言我们可以找到当前位置背后的东西(我们将与文字potassium匹配)
  • \A断言我们在字符串的开头
  • (?:[^\r\n]*\r?\n+)匹配任何不是换行符的字符,后跟换行符
  • {2}量词匹配两次,让我们到第3行
  • [^\r\n]*?懒惰地匹配任意数量的非新线号(我们现在就在第3行)
  • 断言所有这些后,我们可以匹配potassium
  • 在选项2中,我们匹配线上的所有potassium,在后方内部|\G[^\r\n]*?说明 OR 我们之前的位置是紧接在上一场比赛之后的位置,那么任意数量的非换行字符。

答案 1 :(得分:1)

最简单但不是最好的:

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))

答案 2 :(得分:1)

以下正则表达式将匹配仅存在于第三行的字符串pottassium,

potassium(?!\s*\w+[.,])

你的代码就是,

replaced = Regex.Replace(yourString, @"potassium(?!\s*\w+[.,])", "");

DEMO

相关问题