c# - Replace a Word, but Only on a Specific Line -


in application have replace words text appears more 1 line.my text is

most at-home desensitizing toothpastes work numbing nerve , masking pain traditional potassium iron-based toothpastes in form of potassium nitrate, potassium citrate. 

i want replace "potassium" in 3rd line "" only.my code is

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

the problem word removed lines.

how replace 1 word paragraph specific line ?

let's first @ regex (demo here). can change parameters programmatically.

this regex targets first potassium on third line:

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

this replaces bromide:

replaced = regex.replace(yourstring, @"(?<=\a(?:[^\r\n]*\r?\n+){2}[^\r\n]*?)potassium", "bromide"); 

to replace potassium on third line, use \g:

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

with parameters: replacing word on line

to replace word someword on line n, build regex string programmatically. in regex must use n-1, number of lines skip.

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

explanation

  • (?<=\a([^\r\n]*\r?\n+){2}[^\r\n]*?) big lookbehind asserts can find behind current position (at we'll match literal potassium)
  • \a asserts we're @ beginning of string
  • (?:[^\r\n]*\r?\n+) matches number of chars not newline characters, followed newline
  • the {2} quantifier matches twice, getting line 3
  • [^\r\n]*? lazily matches number of non-new line chars (we're on line 3)
  • having asserted that, can match potassium
  • in option 2, match potassium on line, |\g[^\r\n]*? inside lookbehind says or precedes position after previous match, number of non-newline chars.

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -