Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to replace whole line if it contains a particular word

Tags:

c#

.net

regex

I have a word document, it contains some confidential information like it has NIC:343434343. I need a regular expression which will do the following thing.

if it finds NIC on a line it should replace the whole line with specified text.

like image 817
Abdul Rauf Avatar asked Jul 28 '11 10:07

Abdul Rauf


People also ask

How do I match an entire line in regex?

To expand the regex to match a complete line, add ‹ . * › at both ends. The dot-asterisk sequences match zero or more characters within the current line.

How do I replace a word in a regular expression?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

How do you replace a whole line using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


2 Answers

Since by default the dot does not match NewLine, you can simply use

.*NIC.*

to find lines containing "NIC". You'd use this expression like

string result = Regex.Replace(originalString, ".*NIC.*", "replacement string");

You can see it at work at ideone.com.

like image 141
Jens Avatar answered Sep 22 '22 22:09

Jens


Use the start and end-of-line markers:

^.*NIC.*$

^ matches the start of line and $ matches the end of line. This will cause the entire line to be matched, if it contains "NIC" at least once.

like image 33
Anders Abel Avatar answered Sep 25 '22 22:09

Anders Abel