You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C# .NET中如何用正则表达式转换指定字符串为目标格式?

在C# .NET中用正则表达式实现字符串掩码转换

我有以下格式的字符串:

  • PSL44T-VK5VF-2B
  • PSL-44TVK5-VF2B
  • PS-L44-TVK-5VF-2B

需要将它们转换为对应的目标格式:

  1. XXXXXX-XXXX-XX <- PSL44T-VK5VF-2B
  2. PSL-XXXXXX-XXXX <- PSL-44TVK5-VF2B
  3. XX-XXX-XXX-XXX-2B <- PS-L44-TVK-5VF-2B
  4. XX-L44-XXX-XXX-XX <- PS-L44-TVK-5VF-2B

实现思路

每个转换场景对应不同的正则替换逻辑,核心是匹配指定位置的字符段,将需要掩码的段替换为对应长度的X,保留需要显示的段,最后拼接原字符串。

具体实现代码

以下是C#中针对每个场景的正则替换代码:

场景1:全段掩码(按原段长度替换为X)

string input1 = "PSL44T-VK5VF-2B";
// 匹配每个连字符分隔的段,将每个字符替换为对应数量的X,再拼接原字符串
string result1 = Regex.Replace(input1, @"([^-]+)", m => new string('X', m.Value.Length)) + " <-  " + input1;
// 输出结果:XXXXXX-XXXX-XX <-  PSL44T-VK5VF-2B

场景2:保留第一段,掩码后两段

string input2 = "PSL-44TVK5-VF2B";
// 匹配第一段后所有连字符分隔的段,替换为对应长度的X
string result2 = Regex.Replace(input2, @"(?<=^[^-]+-)([^-]+)", m => new string('X', m.Value.Length)) + " <- " + input2;
// 输出结果:PSL-XXXXXX-XXXX <- PSL-44TVK5-VF2B

场景3:保留最后一段,掩码前四段

string input3 = "PS-L44-TVK-5VF-2B";
// 匹配最后一段之前的所有段,替换为对应长度的X
string result3 = Regex.Replace(input3, @"([^-]+)(?=-[^-]+$)", m => new string('X', m.Value.Length)) + " <- " + input3;
// 输出结果:XX-XXX-XXX-XXX-2B <- PS-L44-TVK-5VF-2B

场景4:保留第二段,掩码其他段

string input4 = "PS-L44-TVK-5VF-2B";
// 匹配除第二段外的所有段,替换为对应长度的X
string result4 = Regex.Replace(input4, @"^[^-]+|(?<=-)[^-]+(?=-)|(?<=-)[^-]+$", m => 
    m.Value == "L44" ? m.Value : new string('X', m.Value.Length)) + " <- " + input4;
// 输出结果:XX-L44-XXX-XXX-XX <- PS-L44-TVK-5VF-2B

代码说明

  • 正则通过正向/反向预查定位需要掩码的段,不会破坏原字符串的连字符结构。
  • 用Regex.Replace的委托重载动态生成对应长度的X串,保证掩码长度与原段完全一致。
  • 最后拼接<-和原字符串,完成目标格式构建。

内容的提问来源于stack exchange,提问作者Varanasi Phaneendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:05:24