[英]Replace a Word, but Only on a Specific Line
在我的應用程序中,我必須替換文本中出現的多於一行的單詞。
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", "");
問題是該單詞已從所有行中刪除。
如何替換特定行中段落中的任何一個單詞?
讓我們首先看一下正則表達式( 這里的演示 )。 然后,您可以以編程方式更改參數。
此正則表達式的目標是第三行上的第一個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
使用參數:在任何行上替換任何單詞
要替換第n
行上的單詞someword
,以編程方式構建正則表達式字符串。 在正則表達式中,您必須使用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
potassium
, |\\G[^\\r\\n]*?
在后方的內部說“ 或”是在我們之前的是上一場比賽之后的位置,然后是任意數量的非換行符。 最簡單但不是最好的:
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))
下面的正則表達式將匹配僅在第三行中出現的字符串鉀,
potassium(?!\s*\w+[.,])
您的代碼將是
replaced = Regex.Replace(yourString, @"potassium(?!\s*\w+[.,])", "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.