C# - 用分号替换换行符

时间:2014-05-19 14:45:18

标签: c# regex

使用C#,我现在尝试使用正则表达式用分号(;)替换文本文件中的换行符(\ n),但是只要该行中有任何内容;

如果文本文件是:

This is the program

Hello World

然后我的回归将是

This is the program;

Hello World;

我正在尝试使用

my_str = Regex.Replace(val, "\n", ";");

但它也会影响没有内容的行。

2 个答案:

答案 0 :(得分:3)

试试capturing 1+ characters followed by a newline

(.+)[\r\n]?
\1;\n

C#

my_str = Regex.Replace(val, "(.+)[\r\n]?", "$1;\n");

答案 1 :(得分:0)

我认为这样的事情会起作用。

my_str = Regex.Replace(val, "(?<prev>.+)\\n", "${prev};\\n");