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

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

相关推荐
zdr尽职尽责4 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
BruceNeter5 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
何以解忧唯有撸码7 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手7 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库7 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc8 天前
C# 发展历史
开发语言·c#
kyle~8 天前
C# --- 反射
开发语言·c#
布莱克6058 天前
Swift 字符串详解:从基础用法到性能与最佳实践
服务器·开发语言·ssh·字符串·swift
暴走约伯9 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户7884773163410 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#