简体   繁体   中英

Regex to remove carriage return followed by space

Relatively new to regex, but hoping someone can help. While I've seen loads of examples on how to remove certain characters or combinations of characters, I can't seem to get the following to work for me.

I have a file with the following lines:

a b c
d
ef
 g h
i

What I need is to end up with a string that removes the exact occurrance of newline and space (and only that), so the result would be

a b c
d
efg h
i

Right now I have

string contents = File.ReadAllText("input.text");
string result = Regex.Replace(contents,@"[\n \r]\ ","");
Console.WriteLine(result);

but that only removes the space in front of the gh line, instead of also combining it with the previous line.

What am I doing wrong?

Try using:

string result = Regex.Replace(contents,@"(?s)(?:(?:\r|\n)+ +)","");

(?s) Is to utilise singlie line mode.

string text = Regex.Replace( contents, @"(\r|\n)+^ +", "" , RegexOptions.None | RegexOptions.Multiline );

Mine reads as:

One or more matches of \\r or \\n (new line characters) --> "(\\r|\\n)+"

followed by the beginning of a line --> "^"

followed by one or more spaces --> " +"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM