C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#提取、截取或匹配字符串指定字符

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

作者:hefeng_aspnet

这篇文章主要介绍了使用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<string> ExtractCombinations(string input)
    {
        var results = new List<string>();
        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<RoomInfo> ExtractDetails(string input)
    {
        var results = new List<RoomInfo>();
        // 这里我们假设一个完整的地址结构来一次性提取,这样能对应上哪层是哪个寝
        // 模式: ...层(数字)...(数字)寝...
        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<count; 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
{
    /// <summary>
    /// 提取指定关键字前后的数字组合
    /// </summary>
    /// <param name="input">源字符串</param>
    /// <param name="keyword">关键字,如 "层" 或 "寝"</param>
    /// <param name="position">"Before"表示数字在关键字前(305寝),"After"表示数字在关键字后(层305)</param>
    public static List<string> ExtractByKeyword(string input, string keyword, string position = "After")
    {
        var results = new List<string>();
        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寝
    }
}

总结

以上就是使用C#提取、截取或匹配字符串内包含指定字符的三种方法的详细内容,更多关于C#提取、截取或匹配字符串指定字符的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文