C#基础语法:字符串操作与正则表达式

在C#编程中,字符串操作和正则表达式是处理文本数据的核心技能。字符串操作用于基本文本处理,而正则表达式则提供强大的模式匹配功能。下面我将逐步解释这些概念,并提供示例代码,确保内容真实可靠(基于C#官方文档和标准实践)。所有代码使用C#语言编写。

1. 字符串操作

C#中的字符串是不可变的(即一旦创建不能修改),但提供丰富的方法来操作字符串。常用操作包括创建、连接、分割、替换和提取子字符串。以下是关键方法:

  • 创建字符串:使用string关键字或直接赋值。

    string str1 = "Hello";
    string str2 = "World";
    

  • 常用方法

    • Length:获取字符串长度,例如:$ \text{长度} = \text{str.Length} $。
    • Substring(startIndex, length):提取子字符串。
    • Replace(oldValue, newValue):替换指定字符或子串。
    • Split(separator):分割字符串为数组。
    • Concat(str1, str2)+ 运算符:连接字符串。
    • 其他方法:ToUpper()ToLower()Trim()(去除空白符)。

示例代码:演示基本操作。

using System;

class Program
{
    static void Main()
    {
        string text = "C# Programming is fun!";
        Console.WriteLine("原始字符串: " + text);
        Console.WriteLine("长度: " + text.Length); // 输出: 23
        Console.WriteLine("子字符串: " + text.Substring(0, 2)); // 输出: C#
        Console.WriteLine("替换后: " + text.Replace("fun", "awesome")); // 输出: C# Programming is awesome!
        string[] words = text.Split(' '); // 分割为数组
        Console.WriteLine("分割结果: " + string.Join(", ", words)); // 输出: C#, Programming, is, fun!
        string newText = string.Concat("Learn ", "C#"); // 连接
        Console.WriteLine("连接后: " + newText); // 输出: Learn C#
    }
}

2. 正则表达式

正则表达式(Regex)用于复杂文本模式匹配,如验证邮箱、提取数据等。C#通过System.Text.RegularExpressions命名空间提供支持。核心类包括RegexMatchMatchCollection

  • 基本概念

    • 模式(Pattern):定义匹配规则,例如:$ \d $ 表示数字(等价于[0-9]),$ \w $ 表示单词字符(字母、数字或下划线)。
    • 常用方法:
      • Regex.IsMatch(input, pattern):检查输入是否匹配模式。
      • Regex.Match(input, pattern):获取第一个匹配项。
      • Regex.Matches(input, pattern):获取所有匹配项的集合。
  • 常见模式符号

    • ^:字符串开头。
    • $:字符串结尾。
    • *:零次或多次匹配。
    • +:一次或多次匹配。
    • []:字符类,例如$ [a-z] $ 表示任何小写字母。

示例代码:演示验证邮箱和提取数字。

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // 验证邮箱格式
        string email = "user@example.com";
        string pattern = @"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; // 模式:以单词字符开头,后跟@和域名
        bool isValid = Regex.IsMatch(email, pattern);
        Console.WriteLine("邮箱是否有效: " + isValid); // 输出: True

        // 提取字符串中的数字
        string input = "Order 123, Price 45.6";
        MatchCollection matches = Regex.Matches(input, @"\d+"); // \d+ 匹配一个或多个数字
        Console.WriteLine("提取的数字:");
        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value); // 输出: 123, 45, 6 (注意: 45.6 被分割)
        }
    }
}

3. 最佳实践和总结
  • 字符串操作:优先使用内置方法,避免不必要的字符串创建以提高性能(例如,用StringBuilder处理大量连接)。
  • 正则表达式:保持模式简单,测试边缘情况。使用RegexOptions枚举优化性能(如RegexOptions.IgnoreCase忽略大小写)。
  • 结合使用:字符串操作处理简单任务,正则表达式处理复杂模式。例如,先用Split分割文本,再用Regex匹配特定部分。

通过练习这些基础,您能高效处理C#中的文本数据。建议参考官方文档(如Microsoft Learn)深入学习。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐