温馨提示×

vb怎么在字符串中提取日期

vb
小亿
144
2023-11-07 16:15:03
栏目: 编程语言

在VB中,您可以使用正则表达式或者内置的日期和时间函数来提取日期。

  1. 使用正则表达式提取日期:
Imports System.Text.RegularExpressions

Dim input As String = "今天是2022年1月1日"
Dim pattern As String = "(\d{4})年(\d{1,2})月(\d{1,2})日"
Dim match As Match = Regex.Match(input, pattern)

If match.Success Then
    Dim year As Integer = Integer.Parse(match.Groups(1).Value)
    Dim month As Integer = Integer.Parse(match.Groups(2).Value)
    Dim day As Integer = Integer.Parse(match.Groups(3).Value)

    Dim dateValue As New DateTime(year, month, day)
    Console.WriteLine(dateValue.ToString("yyyy/MM/dd"))
Else
    Console.WriteLine("没有找到日期")
End If
  1. 使用内置的日期和时间函数提取日期:
Dim input As String = "2022年1月1日"
Dim formats() As String = {"yyyy年M月d日", "yyyy/M/d"}

Dim dateValue As DateTime
If DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue) Then
    Console.WriteLine(dateValue.ToString("yyyy/MM/dd"))
Else
    Console.WriteLine("无法解析日期")
End If

以上代码示例中,我们假设输入的字符串中包含"2022年1月1日"这样的日期格式。您可以根据实际情况调整正则表达式或者日期格式。

0