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

如何检测文本框中特定格式字符组合并提取至另一文本框?

解决方案

正则表达式匹配规则

针对你需要的格式(三段各3位字母/数字,用连字符分隔,如FSX-TVD-D5M),可以使用以下正则表达式:
如果要在长字符串中提取符合格式的片段,用这个:

[A-Za-z0-9]{3}-[A-Za-z0-9]{3}-[A-Za-z0-9]{3}

如果需要严格匹配整行内容(比如单独输入的字符串是否完全符合格式),则加上首尾锚点:

^[A-Za-z0-9]{3}-[A-Za-z0-9]{3}-[A-Za-z0-9]{3}$

C# WinForms 实现代码

假设你有两个TextBox控件:sourceTextBox(输入长字符串)和targetTextBox(输出匹配结果),以下是直接可用的代码示例:

提取单个匹配结果

using System.Text.RegularExpressions;

// 绑定到按钮点击或文本变更事件的方法
private void ExtractSingleMatch()
{
    string input = sourceTextBox.Text;
    string pattern = @"[A-Za-z0-9]{3}-[A-Za-z0-9]{3}-[A-Za-z0-9]{3}";
    Match match = Regex.Match(input, pattern);

    if (match.Success)
    {
        targetTextBox.Text = match.Value;
    }
    else
    {
        targetTextBox.Text = "未找到符合格式的内容";
    }
}

提取所有匹配结果(长字符串中有多个符合格式的内容)

using System.Text.RegularExpressions;
using System.Linq;

private void ExtractAllMatches()
{
    string input = sourceTextBox.Text;
    string pattern = @"[A-Za-z0-9]{3}-[A-Za-z0-9]{3}-[A-Za-z0-9]{3}";
    MatchCollection matches = Regex.Matches(input, pattern);

    if (matches.Count > 0)
    {
        targetTextBox.Text = string.Join(Environment.NewLine, matches.Cast<Match>().Select(m => m.Value));
    }
    else
    {
        targetTextBox.Text = "未找到符合格式的内容";
    }
}

说明

  • Regex.Match:仅返回第一个匹配到的结果,适合只需要单个目标的场景
  • Regex.Matches:返回所有符合规则的结果,适合多目标提取场景
  • 若只需匹配大写字母,可将正则中的[A-Za-z0-9]改为[A-Z0-9]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:10:46