C#拆分字符串正则表达式Regex.Split和String.Split方法

 更新时间:2024年04月28日 11:22:35   作者:wenchm  
这篇文章主要给大家介绍了关于C#拆分字符串正则表达式Regex.Split和String.Split方法的相关资料,在C#中,Regex.Split方法和string.Split方法都用于分割字符串,但它们有一些重要的区别,文中通过代码详细讲解下,需要的朋友可以参考下

前言

使用正则表达式可以拆分指定的字符串。同样地,使用字符串对象的Split方法也可以实现此功能。使用字符串对象的Split方法可以根据用户选择的拆分条件,方便地将字符串对象拆分为多个字符串。

一、使用的方法

1.使用Split(String, String)方法

在由正则表达式模式定义的位置将输入字符串拆分为一个子字符串数组。

public static string[] Split (string input, string pattern);
参数
input    String
要拆分的字符串。

pattern    String
要匹配的正则表达式模式。

返回
String[]
字符串数组。

例外
ArgumentException
出现正则表达式分析错误。

ArgumentNullException
input 或 pattern 为 null。

RegexMatchTimeoutException
发生超时。 有关超时的详细信息,请参阅“备注”部分。
// 用正则表达式拆分字符串为一个子字符串数组
using System.Text.RegularExpressions;

namespace _086_2
{
    public class Example
    {
        public static void Main()
        {
            string input = @"01-31-2024";
            string pattern = @"(-)|(/)";

            foreach (string result in Regex.Split(input, pattern))
            {
                Console.WriteLine("{0}", result);
            }
        }
    }
}
// 运行结果:
/*
01
-
31
-
2024

*/

2.使用String.Split 方法

String对象的Split(Char[])方法,根据指定的分隔字符将字符串拆分为子字符串。

public string[] Split (params char[]? separator);

参数
separator    Char[]
分隔字符的数组、不包含分隔符的空数组或 null。

返回
String[]
一个数组,其元素包含此实例中的子字符串,这些子字符串由 separator 中的一个或多个字符分隔。 有关详细信息,请参阅“备注”部分。
// 将空格字符和制表 \t 符作为分隔符
namespace _086_1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
            string s = "Today\tI'm going to school";
            string[] subs = s.Split(' ', '\t');

            foreach (var sub in subs)
            {
                Console.WriteLine($"Substring: {sub}");
                //Console.WriteLine("Substring: {0}", sub);//等效语句
            }
        }
    }
}
// 运行结果:
/*
Substring: Today
Substring: I'm
Substring: going
Substring: to
Substring: school

 */

下面来分享源代码吧:

二、源代码

1.源码

// 使用Split(String, String)方法拆分字符串
// 使用String对象的Split(Char[])方法拆字符串。
using System.Text.RegularExpressions;
namespace _086
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private Button? button2;
        private Button? button1;
        private TextBox? textBox2;
        private TextBox? textBox1;
        private Label? label2;
        private Label? label1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(6, 23),
                Name = "label1",
                Size = new Size(68, 17),
                TabIndex = 0,
                Text = "源字符串:"
            };
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(6, 48),
                Name = "label2",
                Size = new Size(68, 17),
                TabIndex = 1,
                Text = "子字符串:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(72, 17),
                Name = "textBox1",
                Size = new Size(262, 23),
                TabIndex = 2
            };
            // 
            // textBox2
            // 
            textBox2 = new TextBox
            {
                Font = new Font("Microsoft YaHei UI", 7F),
                Location = new Point(72, 48),
                Multiline = true,
                Name = "textBox2",
                Size = new Size(181, 153),
                TabIndex = 3
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(259, 48),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 4,
                Text = "拆分1",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // button2
            // 
            button2 = new Button
            {
                Location = new Point(259, 74),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 5,
                Text = "拆分2",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(340, 207),
                TabIndex = 0,
                TabStop = false,
                Text = "拆分字符串"
            };
            groupBox1.Controls.Add(button2);
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label2);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(364, 231);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "使用正则表达式拆分字符串";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
        }
        /// <summary>
        /// 拆分1:使用正则表达式根据数字进行拆分
        /// 遍历拆分后的字符串集合
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            if (textBox1!.Text != "")
            {
                textBox2!.Text = "";
                string[] str = MyRegex().Split(textBox1!.Text);
                foreach (string s in str)
                {
                    textBox2!.Text += s + Environment.NewLine;
                }
            }
            else
            {
                MessageBox.Show("源字符串不能为空", "拆分1");
            }
        }
        /// <summary>
        /// 拆分2
        /// </summary>
        private void Button2_Click(object? sender, EventArgs e)
        {
            if(textBox1!.Text != "")
            {
                textBox2!.Text = "";
                string s = textBox1!.Text;
                char[] separators = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

                string[] subs = s.Split(separators/*, StringSplitOptions.RemoveEmptyEntries*/);//注释后与正则方法输出相同结果

                foreach (var sub in subs)
                {
                    textBox2!.Text += sub + Environment.NewLine;
                }
            }
            else
            {
                MessageBox.Show("源字符串不能为空", "拆分2");
            }
        }

        [GeneratedRegex("[1-9]")]
        private static partial Regex MyRegex();
    }
}

2.生成效果

总结

到此这篇关于C#拆分字符串正则表达式Regex.Split和String.Split方法的文章就介绍到这了,更多相关C#正则表达式Regex.Split和String.Split内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

相关文章

  • C#实现插入排序算法实例

    C#实现插入排序算法实例

    这篇文章主要介绍了C#实现插入排序算法,实例分析了插入排序算法的原理与实现技巧,需要的朋友可以参考下
    2015-05-05
  • C#判断ip地址是否可以ping的通

    C#判断ip地址是否可以ping的通

    这篇文章主要介绍了ip地址是否可以ping的通的方法,使用到了C#,需要的朋友可以参考下
    2014-06-06
  • C#如何Task执行任务,等待任务完成

    C#如何Task执行任务,等待任务完成

    这篇文章主要介绍了C#如何Task执行任务,等待任务完成,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • C# AttributeUsage使用案例详解

    C# AttributeUsage使用案例详解

    这篇文章主要介绍了C# AttributeUsage使用案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • 在WPF中实现平滑滚动的方法详解

    在WPF中实现平滑滚动的方法详解

    这篇文章介绍了WPF实现平滑滚动的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • Unity UGUI实现滑动翻页直接跳转页数

    Unity UGUI实现滑动翻页直接跳转页数

    这篇文章主要为大家详细介绍了Unity UGUI实现滑动翻页,直接跳转页数,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • C#获取web.config配置文件内容的方法

    C#获取web.config配置文件内容的方法

    这篇文章主要介绍了C#获取web.config配置文件内容的方法,涉及C#配置文件属性获取的相关技巧,需要的朋友可以参考下
    2015-05-05
  • C#基于winform实现音乐播放器

    C#基于winform实现音乐播放器

    这篇文章主要为大家详细介绍了C#基于winform实现音乐播放器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C#中尾递归的使用、优化及编译器优化

    C#中尾递归的使用、优化及编译器优化

    这篇文章主要介绍了C#中尾递归的使用、优化及编译器优化,本文讲解了递归运用、尾递归优化、编译器优化等内容,需要的朋友可以参考下
    2015-04-04
  • C#实现将HTML转换成纯文本的方法

    C#实现将HTML转换成纯文本的方法

    这篇文章主要介绍了C#实现将HTML转换成纯文本的方法,基于自定义类实现文本转换功能,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07

最新评论