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

如何在VB.NET中拆分文件名提取日期、产品等信息

VB.NET 拆分文件名提取指定信息方案

针对文件名(14-07-2022-Pencil-200 (Zane)),可以通过字符串处理或正则表达式两种方式提取目标信息,以下是具体实现代码:

方法一:字符串拆分法

这种方式适合结构固定的文件名,逻辑直观易懂:

' 原始文件名
Dim originalFileName As String = "(14-07-2022-Pencil-200 (Zane))"

' 1. 去除外层括号,提取核心内容
Dim coreContent As String = originalFileName.Trim("("c, ")"c)

' 2. 按"-"拆分前四部分(日期、产品、数量+买家)
Dim parts() As String = coreContent.Split("-"c)

' 3. 处理日期:去除月份前导零
Dim dateParts() As String = parts(0).Split("-"c)
Dim formattedDate As String = $"{dateParts(0)}-{CInt(dateParts(1))}-{dateParts(2)}"

' 4. 获取产品名称
Dim productName As String = parts(1)

' 5. 拆分数量和买家信息
Dim quantityBuyerPart As String = parts(2)
Dim quantity As String = quantityBuyerPart.Split("("c)(0).Trim()
Dim buyerName As String = quantityBuyerPart.Split("("c)(1).Trim(")"c)

' 6. 赋值到对应TextBox
TextBox1.Text = formattedDate
TextBox2.Text = productName
TextBox3.Text = quantity
TextBox4.Text = buyerName

方法二:正则表达式法

如果文件名结构有细微变化(比如分隔符或括号格式),正则表达式的适配性更强:

Imports System.Text.RegularExpressions

' 原始文件名
Dim originalFileName As String = "(14-07-2022-Pencil-200 (Zane))"

' 定义正则匹配模式,捕获日期、产品、数量、买家四个分组
Dim pattern As String = "\((\d{2})-(\d{2})-(\d{4})-(\w+)-(\d+)\s*\((\w+)\)\)"
Dim match As Match = Regex.Match(originalFileName, pattern)

If match.Success Then
    ' 处理日期:去除月份前导零
    Dim formattedDate As String = $"{match.Groups(1).Value}-{CInt(match.Groups(2).Value)}-{match.Groups(3).Value}"
    ' 赋值到对应TextBox
    TextBox1.Text = formattedDate
    TextBox2.Text = match.Groups(4).Value
    TextBox3.Text = match.Groups(5).Value
    TextBox4.Text = match.Groups(6).Value
Else
    ' 匹配失败时的提示(可选)
    MessageBox.Show("文件名格式不符合预期")
End If

代码说明

  • 字符串拆分法:通过Trim去除外层括号,Split按分隔符拆分字符串,再分别处理各部分内容,适合结构完全固定的场景。
  • 正则表达式法:通过分组捕获直接提取目标内容,即使文件名有少量格式变化(比如数量和买家之间的空格多少),也能正常匹配,灵活性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:36:23