Replace Line in string

Asked

Viewed 43 times

0

I’m creating a C# application using Replace(), i can replace a specific word by another in the entire file, but I wonder if there is a way to do this replace in just one specific line.

I want the code to trace the line and then do the Replace() only on that specific line without harming the rest of the file.

  • I updated! I tried to be clearer and objective, I hope I was able to explain my problem better

  • With regex on a line, replace the word line with Row on line 7: Regex.Replace(texto_de_entrada, "(?<=^([^\n]+\n){6}[^\r]*)linha(?=[^\r]*.*)", "row", RegexOptions.Singleline)

1 answer

1

It is possible if you have how to know which is line 7. Of course, as long as there is no possibility of confusion with other parties. You changed everything to . and on line 7 will return from . for ,. But let’s just say I already had something with . there before changing , for ., that . that was already there will turn ,. Is that what you want? If it is, ok. If there is no possibility of having a . previous, ok, can do.

If it is not possible you can still do line by line and skipping line 7. But be careful if doing several replace() will have a lot of memory allocation. In certain applications this is no problem, but be aware that there will be pressure on the Garbage Collector and in extreme cases there may be memory exhaustion. Even with a replace() there will be a little pressure, today has techniques to do this more efficiently, but in this case it is probably excessive concern.

In the last case I could do manually analyzing each character, but if you do not know will have poor performance.

  • Friend, in case the line 7 always has a "7252" information followed by the Windows address with the location of a PNG file (image). Type: 7252 - c:/directory/face.png So I think how it comes to always be a Windows address if you don’t have comma pq you can’t use. In the case the tool I am creating enters the txt file and replaces all "," po"r ." In this case, line 7 remains intact because it has no commas. After that I have another button that does the reverse process, and that ends up modifying line 7 and it is in this process that I want to preserve this line

  • For me the question began to lose its meaning now.

  • I’m sorry, I guess I’m not explaining my problem correctly, but basically I’d like to know if there’s any way to do Replace on just one specific line? If yes, how? I did some research but found nothing specific to just a certain line

Browser other questions tagged

You are not signed in. Login or sign up in order to post.