文字列から日付を抽出する方法は?

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日”などの日付形式が入力文字列に含まれると想定しています。必要に応じて、正規表現または日付形式を調整してください。

bannerAds