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

目录

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

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

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

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

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

[3. 完整示例代码](#3. 完整示例代码)

关键点总结


如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

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.Groups1.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.Groups1.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)

{

// Group1 对应 "层(\d+)" 中的数字

// Group2 对应 "(\d+)寝" 中的数字

if (!string.IsNullOrEmpty(match.Groups1.Value))

return match.Groups1.Value;

else if (!string.IsNullOrEmpty(match.Groups2.Value))

return match.Groups2.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.Groups1.Value;

}

// 尝试匹配 "寝" 前面的数字

Match matchQin = Regex.Match(input, @"(\d+)寝");

if (matchQin.Success)

{

return matchQin.Groups1.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 方案则需要更复杂的逻辑来确保索引正确。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
samble9 小时前
从零搭建灌装监控系统(十九):单元测试实战,xUnit + 内存SQLite + 反射测试私有方法
c#·wpf·mvvm·modbus·工业控制
Logic10112 小时前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
人道领域12 小时前
【面试八股速通篇01】锁与并发工具
java·开发语言·面试·c#
宇卿.12 小时前
C#字段、属性、索引器、常量
开发语言·计算机视觉·c#
程序员Linc13 小时前
ONNXOCRSharp 开源手记 02|v0.4.0 PDF识别
开发语言·pdf·c#·ocr·onnxocrsharp
慧都小妮子13 小时前
MSG 附件太占内存?Aspose.Email for .NET 26.9 延迟加载
c#·.net·aspose·内存优化·延迟加载·aspose.email·附件内存
慧都小妮子14 小时前
FastReport PDF/UA 导出:让出海 PDF 满足无障碍合规要求
pdf·c#·fastreport·报表导出·pdf/ua·pdf 无障碍
淡海水17 小时前
03-02-架构篇-Boehm GC架构解析
unity·架构·c#·gc·boehm
samble1 天前
从零搭建灌装监控系统(十八):自定义控件,三色灯与状态指示
c#·wpf·mvvm·modbus·工业控制
jun_bai1 天前
使用Aspose实现word文档合并,内容替换
windows·c#·word