如何使用regex不留行空间

本文关键字:空间 何使用 regex | 更新日期: 2023-09-27 18:30:03

我的richtexBox1上有以下句子。如果句子以Create table开头,以分号结尾,我可以在每行之间只留一行空格吗

结果:

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();

如何使用regex不留行空间

只需使用此即可

 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();
    }

感谢您澄清您的问题:

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;