怎样在C#中文档里面查找日期并替换成加粗的

三个文本框是生成正文的文档,每个文档代表一个段落,在每个段落查找日期并替换成加粗的

img

要在C# Winform应用程序中实现文本加粗,使用TextBox控件是不行的,得用RichTextBox控件,这里我使用C# Winform(.NET 6)为你写了一个示例,

先看运行效果,如图:

img

代码如下:

**Form1.cs **

using System.Text;
using System.Text.RegularExpressions;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSearchAndReplace_Click(object sender, EventArgs e)
        {
            var text = rtxtParagraph.Text;
            var pattern = @"(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?";
            var r = new Regex(pattern);
            var result = Regex.Replace(text, pattern, m => Replace(m.Value));
            rtxtResult.Rtf = MakeBold(result);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            rtxtParagraph.Text = $"现在是北京时间{DateTime.Now:yyyy-MM-dd HH:mm:ss},正在为CSDN的网友(pixiuz)解决关于《怎样在C#中文档里面查找日期并替换成加粗的》,他发布问题的时间是:2021-12-13";
        }

        public string Replace(string text)
        {
            var returnValue = text.Replace(text, @"\b " + text + @" \b0 ");
            return returnValue.ToString();
        }

        public string MakeBold(string text)
        {
            var finalString = new StringBuilder();
            finalString.Append(@"{\rtf1\charset134");
            finalString.Append(text);
            finalString.Append(@"}");
            return finalString.ToString();
        }
    }
}

Form1.Designer.cs

namespace WinFormsApp1
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnSearchAndReplace = new System.Windows.Forms.Button();
            this.rtxtParagraph = new System.Windows.Forms.RichTextBox();
            this.rtxtResult = new System.Windows.Forms.RichTextBox();
            this.SuspendLayout();
            // 
            // btnSearchAndReplace
            // 
            this.btnSearchAndReplace.Location = new System.Drawing.Point(12, 12);
            this.btnSearchAndReplace.Name = "btnSearchAndReplace";
            this.btnSearchAndReplace.Size = new System.Drawing.Size(92, 23);
            this.btnSearchAndReplace.TabIndex = 0;
            this.btnSearchAndReplace.Text = "查找并替换";
            this.btnSearchAndReplace.UseVisualStyleBackColor = true;
            this.btnSearchAndReplace.Click += new System.EventHandler(this.btnSearchAndReplace_Click);
            // 
            // rtxtParagraph
            // 
            this.rtxtParagraph.Location = new System.Drawing.Point(13, 42);
            this.rtxtParagraph.Name = "rtxtParagraph";
            this.rtxtParagraph.Size = new System.Drawing.Size(664, 117);
            this.rtxtParagraph.TabIndex = 1;
            this.rtxtParagraph.Text = "";
            // 
            // rtxtResult
            // 
            this.rtxtResult.Location = new System.Drawing.Point(13, 200);
            this.rtxtResult.Name = "rtxtResult";
            this.rtxtResult.Size = new System.Drawing.Size(664, 117);
            this.rtxtResult.TabIndex = 2;
            this.rtxtResult.Text = "";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(689, 354);
            this.Controls.Add(this.rtxtResult);
            this.Controls.Add(this.rtxtParagraph);
            this.Controls.Add(this.btnSearchAndReplace);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private Button btnSearchAndReplace;
        private RichTextBox rtxtParagraph;
        private RichTextBox rtxtResult;
    }
}

原来的方案只是根据你题目的大意来实现,对你要把文本保存到Word文档的需求进行了改进,示例代码如下:

using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnSearchAndReplace_Click(object sender, EventArgs e)
        {
            var text = rtxtParagraph.Text;
            rtxtResult.Text = rtxtParagraph.Text;
            var pattern = @"(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?";
            var matches = Regex.Matches(text, pattern);
            var font = rtxtParagraph.Font;
            foreach (Match match in matches)
            {
                if (!match.Success) continue;
                rtxtResult.SelectionStart = match.Index;
                rtxtResult.SelectionLength = match.Length;
                rtxtResult.SelectionFont = new Font(font, FontStyle.Bold | FontStyle.Italic);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            rtxtParagraph.Text = $"现在是北京时间{DateTime.Now:yyyy-MM-dd HH:mm:ss},正在为CSDN的网友(pixiuz)解决关于《怎样在C#中文档里面查找日期并替换成加粗的》,他发布问题的时间是:2021-12-13";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            rtxtResult.SaveFile(@"d:\tmp\1.doc", RichTextBoxStreamType.RichText);
            MessageBox.Show("文档保存成功");
        }
    }
}

运行效果如图:

img