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. 使用 SubstringIndexOf(适用于格式极其固定的情况)

如果字符串格式非常严格(例如永远是"层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 方案则需要更复杂的逻辑来确保索引正确。

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

相关推荐
TeamDev2 小时前
JxBrowser 9.3.0 版本发布啦!
java·后端·c#·混合应用·jxbrowser·浏览器控件·异步媒体设备
梦帮科技3 小时前
UE5 GAS 实战:用 Gameplay Ability System 搭建「赛博修真」境界与技能体系
c++·人工智能·python·ue5·c#
hez20104 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉9 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫10 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫11 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m62512 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户917215619021112 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠12 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net