我有一个文字,来自文本文件,它的名字是Lucky.ini
[组别1]
数字= 0811
优惠券= 0118
[第2组]
数字= 4852
优惠券= 7112
如何将此文本读取到文本框,但我想读取" ="之后的数字。 我有两个小组。 首先,便宜和 第二,富有
答案 0 :(得分:0)
我使用Regex来解析文本文件。见下面的代码
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Data
Public Class Form1
Const FILENAME As String = "c:\temp\test.txt"
'[Group1]
'Number = 0811
'Coupon = 0118
'[Group2]
'Number = 4852
'Coupon = 7112
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Dim dt As New DataTable
dt.Columns.Add("Group", GetType(String))
dt.Columns.Add("Number", GetType(String))
dt.Columns.Add("Coupon", GetType(String))
Dim input As String = File.ReadAllText(FILENAME)
Dim pattern As String = "[^\[]*\[(?'name'[^\]]+)\]\s*Number\s+=\s*(?'number'\d+)\s*Coupon\s*=\s*(?'coupon'\d+)"
Dim expr As New Regex(pattern, RegexOptions.Singleline)
Dim matches As MatchCollection = expr.Matches(input)
For Each m As Match In matches
Dim name As String = m.Groups("name").Value
Dim number As String = m.Groups("number").Value
Dim coupon As String = m.Groups("coupon").Value
dt.Rows.Add(New String() {name, number, coupon})
Next m
DataGridView1.DataSource = dt
Dim richNumber = dt.Rows(0)("number")
Dim richCoupon = dt.Rows(0)("coupon")
Dim cheapNumber = dt.Rows(1)("number")
Dim cheapCoupon = dt.Rows(1)("coupon")
End Sub
End Class