如何使用正则表达式创建行间距?

时间:2013-09-04 06:06:54

标签: c# regex winforms richtextbox

我的richtexBox1下面有句子,我可以在每一行之间只有一个行间距,如果句子以Create表开头并以semicolomn结尾,则不要创建任何行间距

结果:

ALTER TABLE "COURSE" DROP CONSTRAINT "CRSE_CRSE_FK";




ALTER TABLE "ENROLLMENT" DROP CONSTRAINT "ENR_STU_FK";

ALTER TABLE "ENROLLMENT" DROP CONSTRAINT "ENR_SECT_FK"; 

ALTER TABLE "ENROLLMENT" ADD CONSTRAINT "ENR_STU_FK" FOREIGN KEY ("STUDENT_ID") REFERENCES "STUDENT"("STUDENT_ID") ENABLE;

ALTER TABLE "ENROLLMENT" ADD CONSTRAINT "ENR_SECT_FK" FOREIGN KEY ("SECTION_ID") REFERENCES "SECTION"("SECTION_ID") ENABLE;


CREATE TABLE "COMP1" 
(   "EMPID" NUMBER, 
"EMPLNAME" VARCHAR2(20), 
"EMPFNAME" VARCHAR2(20), 
"DEPTNO" NUMBER, 
"MGRID" NUMBER, 
PRIMARY KEY ("EMPID") ENABLE
);

CREATE TABLE "COMP12" 
(   "EMPID" NUMBER, 
"EMPLNAME" VARCHAR2(20), 
"EMPFNAME" VARCHAR2(20), 
"DEPTNO" NUMBER, 
"MGRID" NUMBER, 
PRIMARY KEY ("EMPID") ENABLE
);

预期结果

    ALTER TABLE "COURSE" DROP CONSTRAINT "CRSE_CRSE_FK";  

    ALTER TABLE "ENROLLMENT" DROP CONSTRAINT "ENR_STU_FK";

    ALTER TABLE "ENROLLMENT" DROP CONSTRAINT "ENR_SECT_FK"; 

    ALTER TABLE "ENROLLMENT" ADD CONSTRAINT "ENR_STU_FK" FOREIGN KEY ("STUDENT_ID") REFERENCES "STUDENT"("STUDENT_ID") ENABLE;

    ALTER TABLE "ENROLLMENT" ADD CONSTRAINT "ENR_SECT_FK" FOREIGN KEY ("SECTION_ID") REFERENCES "SECTION"("SECTION_ID") ENABLE;        

    CREATE TABLE "COMP1" 
    (   "EMPID" NUMBER, 
    "EMPLNAME" VARCHAR2(20), 
    "EMPFNAME" VARCHAR2(20), 
    "DEPTNO" NUMBER, 
    "MGRID" NUMBER, 
    PRIMARY KEY ("EMPID") ENABLE
    );

    CREATE TABLE "COMP12" 
    (   "EMPID" NUMBER, 
    "EMPLNAME" VARCHAR2(20), 
    "EMPFNAME" VARCHAR2(20), 
    "DEPTNO" NUMBER, 
    "MGRID" NUMBER, 
    PRIMARY KEY ("EMPID") ENABLE
    );

我的代码(仅添加2行空白)

           List<string> rt = new List<string>();
            foreach (string line in richtexBox1 .Lines)
            {
                if (line != "")
                {
                    rt.Add(line);
                    rt.Add("");
                }
            }
            richtexBox1 .Lines = rt.ToArray();

2 个答案:

答案 0 :(得分:1)

试试这个

 private void button1_Click(object sender, EventArgs e)
    {
        List<string> rt = new List<string>();
        foreach (string line in richTextBox1.Lines)
        {
            if (!string.IsNullOrEmpty(line.Trim()))
            {
                rt.Add(line);
            }
            if (line.Trim().EndsWith(";"))
            {
                rt.Add("\n");
            }
        }
        richTextBox1.Lines = rt.ToArray();
        richTextBox1.Refresh();
    }

答案 1 :(得分:0)

感谢您澄清问题:

while (richTextBox1.Text.Contains("\n\n"))
    richTextBox1.Text = richTextBox1.Text.Replace("\n\n", "\n");
string[] linesafter = richTextBox1.Lines;
for (int i = 0; i < richTextBox1.Lines.Length; i++)
    if (richTextBox1.Lines[i].EndsWith(";"))
        linesafter[i] = linesafter[i] + "\n";
richTextBox1.Lines = linesafter;