开发者

RegEx to replace pattern in text file containing carriage returns (using Notepad2 and C#)

开发者 https://www.devze.com 2023-03-09 23:40 出处:网络
I have a text file containing the following string: --jonesj (release 00) 开发者_如何学编程some sql goes here

I have a text file containing the following string:

--jonesj (release 00)
开发者_如何学编程some sql goes here

--jonesj (release 01)
some sql goes here

--smithb (release 01)
some sql goes here

What I want to do is replace all commented-out SQL with an empty string. The resulting string would look like this:

some sql goes here

some sql goes here

some sql goes here

Using Notepad2 as my testing grounds before implementing this in my code, I am trying the RegEx of ^--.*$. However, this appears to be highlighting the entire text file. I am terrible at RegEx and hope someone can help me along here.


You can get this to work by explicitly matching the end of line chars \r\n in Multiline mode. This has the benefit of replacing the newlines too (i.e no empty line where the comment was)

var input=@"--jonesj (release 00)
some sql goes here

--jonesj (release 01)
some sql goes here

--smithb (release 01)
some sql goes here";

var cleaned=Regex.Replace(
    input,
    @"^--.*(\r)?\n",
    string.Empty,
    RegexOptions.Multiline)


I think you can get away with this:

var pieces = Regex.Split(input, "--[^\(]*\(release \d\d\)");


You can use ^--[^\n\r]*$ to make sure the wild card won't match newlines and in greedy mode just match the whole file.

0

精彩评论

暂无评论...
验证码 换一张
取 消