C#教程

关注公众号 jb51net

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

C#截取或匹配字符串内包含指定字符的方法

作者:hefeng_aspnet

在 C# 中,处理包含变化数字的字符串匹配或截取,最灵活且推荐的方式是使用‌正则表达式(Regular Expressions)‌,此外,如果格式非常固定,也可以使用简单的字符串处理方法,所以本文给大家介绍了使用C#截取或匹配字符串内包含指定字符的方法,需要的朋友可以参考下

C# 截取或匹配字符串内包含指定字符,如:层305、层101或305寝、101寝等,其中数字是变化的。

在 C# 中,处理包含变化数字的字符串匹配或截取,最灵活且推荐的方式是使用‌正则表达式(Regular Expressions)‌。此外,如果格式非常固定,也可以使用简单的字符串处理方法。

以下是几种常见场景的解决方案:

1. 使用正则表达式匹配并提取数字(推荐)

正则表达式可以精准地定位“层”或“寝”前后的数字,无论数字是多少位。

场景 A:提取“层”后面的数字(如 “层305” -> 305)

using System;
using System.Text.RegularExpressions;
public class StringHelper
{
    public static string ExtractNumberAfterLayer(string input)
    {
        // 模式解释:
        // "层"   : 匹配 literal 字符 "层"
        // (\d+)  : 捕获组,匹配一个或多个数字
        string pattern = @"层(\d+)";
        Match match = Regex.Match(input, pattern);
        if (match.Success)
        {
            return match.Groups[1].Value; // 返回捕获组中的数字部分
        }
        return null; // 未找到匹配
    }
}

场景 B:提取“寝”前面的数字(如 “305寝” -> 305)

public static string ExtractNumberBeforeQin(string input)
{
    // 模式解释:
    // (\d+)  : 捕获组,匹配一个或多个数字
    // "寝"   : 匹配 literal 字符 "寝"
    string pattern = @"(\d+)寝";
    Match match = Regex.Match(input, pattern);
    if (match.Success)
    {
        return match.Groups[1].Value;
    }
    return null;
}

场景 C:通用提取(同时兼容 “层305” 和 “305寝”)

如果你希望从同一个字符串中提取出那个核心数字,不管它是在“层”后还是“寝”前:

public static string ExtractRoomNumber(string input)
{
    // 模式解释:
    // 要么匹配 "层" 后面的数字,要么匹配 "寝" 前面的数字
    string pattern = @"(?:层)(\d+)|(\d+)(?:寝)";
    Match match = Regex.Match(input, pattern);
    if (match.Success)
    {
        // Group[1] 对应 "层(\d+)" 中的数字
        // Group[2] 对应 "(\d+)寝" 中的数字
        if (!string.IsNullOrEmpty(match.Groups[1].Value))
            return match.Groups[1].Value;
        else if (!string.IsNullOrEmpty(match.Groups[2].Value))
            return match.Groups[2].Value;
    }
    return null;
}

2. 使用Substring和IndexOf(适用于格式极其固定的情况)

如果字符串格式非常严格(例如永远是“层XXX”或“XXX寝”),可以使用传统字符串操作,但容错性较差。

public static string ExtractWithSubstring(string input)
{
    if (input.Contains("层"))
    {
        int index = input.IndexOf("层");
        // 假设数字紧跟在"层"之后,且直到字符串结束或遇到非数字字符
        string remaining = input.Substring(index + 1);
        // 进一步提取纯数字部分
        return new string(remaining.TakeWhile(char.IsDigit).ToArray());
    }
    else if (input.Contains("寝"))
    {
        int index = input.IndexOf("寝");
        // 假设数字在"寝"之前
        string preceding = input.Substring(0, index);
        // 从末尾向前提取纯数字部分
        return new string(preceding.Reverse().TakeWhile(char.IsDigit).Reverse().ToArray());
    }
    return null;
}

3. 完整示例代码

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        string[] testCases = { "层305", "层101", "305寝", "101寝", "A层305B", "房间305寝" };
        foreach (var test in testCases)
        {
            string number = ExtractRoomNumber(test);
            Console.WriteLine($"输入: {test,-10} => 提取数字: {number}");
        }
    }
    /// <summary>
    /// 通用方法:提取"层"后或"寝"前的数字
    /// </summary>
    static string ExtractRoomNumber(string input)
    {
        if (string.IsNullOrEmpty(input)) return null;
        // 尝试匹配 "层" 后面的数字
        Match matchLayer = Regex.Match(input, @"层(\d+)");
        if (matchLayer.Success)
        {
            return matchLayer.Groups[1].Value;
        }
        // 尝试匹配 "寝" 前面的数字
        Match matchQin = Regex.Match(input, @"(\d+)寝");
        if (matchQin.Success)
        {
            return matchQin.Groups[1].Value;
        }
        return null;
    }
}

输出结果:

输入: 层305       => 提取数字: 305
输入: 层101       => 提取数字: 101
输入: 305寝       => 提取数字: 305
输入: 101寝       => 提取数字: 101
输入: A层305B     => 提取数字: 305
输入: 房间305寝   => 提取数字: 305

关键点总结

  1. 正则表达式 \d+‌:用于匹配一个或多个连续数字,是处理“变化数字”的核心。
  2. 捕获组 ()‌:用于只提取我们关心的数字部分,而不是整个匹配字符串。
  3. Regex.Match‌:用于查找第一个匹配项。如果需要查找所有匹配项(如字符串中有多个房间号),可使用 Regex.Matches
  4. 灵活性‌:正则方案能很好地处理前后有其他字符的情况(如 “A层305B”),而 Substring 方案则需要更复杂的逻辑来确保索引正确。

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

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