首页
看点啥
插画图片
首页 科技看点 使用C#提取、截取或匹配字符串内包含指定字符的三种做法实用指南

使用C#提取、截取或匹配字符串内包含指定字符的三种做法实用指南

2026-10-24 0

平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“采用C#提取、截取或匹配字符串内包含指定字符的三种做法”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。

在这个场景下,C#提取、截取或匹配字符串内包含指定字符,如:5号综合楼3层305寝2号或4号综合楼2层205寝1号。

针对字符串 "5号综合楼3层305寝2号或4号综合楼2层205寝1号",提取“层+数字”(如 层305)或“数字+寝”(如 305寝)这类组合,核心在于采用 正则表达式的捕获组。

以下是几种针对不同需求的 C# 实现方案:

方案一:提取完整的组合字符串(建议)

如果你希望直接得到 "层305"、"305寝" 这样的完整子串,能够采用“或”逻辑的正则。

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Extractor
{
    public static List ExtractCombinations(string input)
    {
        var results = new List();
        if (string.IsNullOrEmpty(input)) return results;
        // 正则解释:
        // (层\d+)  : 匹配 "层" 后面跟着数字,例如 "层305"
        // |        : 或者
        // (\d+寝)  : 匹配 数字 后面跟着 "寝",例如 "305寝"
        string pattern = @"(层\d+)|(\d+寝)";
        MatchCollection matches = Regex.Matches(input, pattern);
        foreach (Match match in matches)
        {
            // match.Value 会返回整个匹配到的文本(无论是 "层305" 还是 "305寝")
            if (match.Success)
            {
                results.Add(match.Value);
            }
        }
        return results;
    }
}
// 调用示例
class Program
{
    static void Main()
    {
        string text = "5号综合楼3层305寝2号或4号综合楼2层205寝1号";
        var items = Extractor.ExtractCombinations(text);
        // 输出: 层305, 305寝, 层205, 205寝
        Console.WriteLine(string.Join(", ", items));
    }
}

方案二:分别提取“层数”和“寝室号”的数字

实际处理时,若你需将“层”和“寝”分开处理,或者只想要纯数字,能够采用分组捕获。

using System;
using System.Text.RegularExpressions;
public class DetailedExtractor
{
    public class RoomInfo
    {
        public string FloorPart { get; set; } // 例如: "层305"
        public int FloorNum { get; set; }     // 例如: 305
        public string RoomPart { get; set; }  // 例如: "305寝"
        public int RoomNum { get; set; }      // 例如: 305
    }
    public static List ExtractDetails(string input)
    {
        var results = new List();
        // 这里我们假设一个完整的地址结构来一次性提取,这样能对应上哪层是哪个寝
        // 模式: ...层(数字)...(数字)寝...
        string pattern = @"层(\d+).+?(\d+)寝"; 
        // 注意:如果字符串里有多个地址,上面的简单正则可能会跨地址匹配。
        // 更严谨的做法是分别提取,或者使用更复杂的非贪婪匹配。
        // 为了演示简单提取所有“层X”和“Y寝”:
        // 1. 提取所有 "层+数字"
        var floorMatches = Regex.Matches(input, @"层(\d+)");
        // 2. 提取所有 "数字+寝"
        var roomMatches = Regex.Matches(input, @"(\d+)寝");
        // 由于原字符串结构对称,我们可以假设第i个层对应第i个寝
        int count = Math.Min(floorMatches.Count, roomMatches.Count);
        for(int i=0; i        {
            results.Add(new RoomInfo
            {
                FloorPart = "层" + floorMatches[i].Groups.Value,
                FloorNum = int.Parse(floorMatches[i].Groups.Value),
                RoomPart = roomMatches[i].Groups.Value + "寝",
                RoomNum = int.Parse(roomMatches[i].Groups.Value)
            });
        }
        return results;
    }
}

方案三:灵活提取特定格式(通用工具方法)

结合项目来看,若你只需一个通用的方法,传入关键字(如“层”或“寝”)来提取相邻数字:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class FlexibleExtractor
{
    ///
    /// 提取指定关键字前后的数字组合
    ///

    /// 源字符串
    /// 关键字,如 "层" 或 "寝"
    /// "Before"表示数字在关键字前(305寝),"After"表示数字在关键字后(层305)
    public static List ExtractByKeyword(string input, string keyword, string position = "After")
    {
        var results = new List();
        if (string.IsNullOrEmpty(input)) return results;
        string pattern = "";
        if (position.Equals("After", StringComparison.OrdinalIgnoreCase))
        {
            // 匹配: 关键字 + 数字 (例如: 层305)
            // \Q...\E 用于转义关键字中的特殊字符,虽然中文通常不需要,但这是好习惯
            pattern = $@"({Regex.Escape(keyword)}\d+)";
        }
        else
        {
            // 匹配: 数字 + 关键字 (例如: 305寝)
            pattern = $@"(\d+{Regex.Escape(keyword)})";
        }
        MatchCollection matches = Regex.Matches(input, pattern);
        foreach (Match match in matches)
        {
            results.Add(match.Groups.Value);
        }
        return results;
    }
}
// 调用示例
class Program
{
    static void Main()
    {
        string text = "5号综合楼3层305寝2号或4号综合楼2层205寝1号";
        // 提取 "层305", "层205"
        var floors = FlexibleExtractor.ExtractByKeyword(text, "层", "After");
        Console.WriteLine("层信息: " + string.Join(", ", floors)); 
        // 输出: 层信息: 层305, 层205
        // 提取 "305寝", "205寝"
        var rooms = FlexibleExtractor.ExtractByKeyword(text, "寝", "Before");
        Console.WriteLine("寝信息: " + string.Join(", ", rooms)); 
        // 输出: 寝信息: 305寝, 205寝
    }
}

总结

  • 最轻松直接:采用方案一的正则 (层\d+)|(\d+寝),它能够一次性把所有符合这两种格式的片段都找出来。
  • 最灵活:采用方案三,借助参数控制是提取“前数字”还是“后数字”,代码复用性高。
  • 关键点:\d+ 代表匹配任意长度的连续数字,这解决了你提到的“数字是变化的”这一需求。

落到代码里,总的来说,C#提取、截取或匹配字符串指定字符适合结合实际项目边做边理解。先抓住核心思路,再逐步补上细节和边界处理,最后效果会更稳定,也更容易复用。

喜欢(0)

上一篇

如何用git clone一个指定文件或者目录实用指南

下一篇

Git仓库过大致使clone失败问题及解决实用指南

Git仓库过大致使clone失败问题及解决实用指南
猜你喜欢