我正在嘗試制作一個 VB.NET Visual Studio 2019 表單,該表單將要求一個文本檔案并在我呼叫的 TextBox 中輸出一個名稱串列,TextBox4因此我不必創建任何檔案(或者可能創建一個文本檔案,將其復制到TextBox4,然后將其洗掉?)。文本檔案中的名稱介于"Customer_Name"和之間"Customer_ID"。除了這兩個識別符號之外,該檔案似乎沒有任何押韻或理由,因此有效地拆分它一直很困難。如果相關的話,每個檔案通常有 100 到 1000 個條目。
樣本(模擬)資料:
"Customer_name":"JOHN DOE","Customer_id":"9251954","Customer_team_id":"HOST","Customer_position_id":"MGR","Customer_short_name":"Joey","Customer_eligibility":"LT5","Customer_page_url":"google.com","Customer_alt_id":"M7","Customer_name":"JANE DOE","Customer_id":"8734817","Customer_team_id":"HOST","Customer_position_id":"TECH","Customer_name":"JOSEPH DOE","Customer_id":"8675307",
我想在文本框中顯示:
JOHN DOE
JANE DOE
JOSEPH DOE
uj5u.com熱心網友回復:
看看這個正則運算式模式:
(?:")(?<key>\w )(?:":")(?<value>((\w|\s|\.)) )(?:",)
這做了幾件事:
(?:")- 創建非捕獲組以匹配開引號(?<key>\w )- 創建一個命名組以匹配鍵(例如 Customer_name)(?:":")- 創建一個非捕獲組來匹配右引號、冒號和左引號(?<value>((\w|\s|\.)) )- 創建一個命名組以匹配值(例如 John Doe)(?:",)- 創建一個非捕獲組以匹配右引號
有了這個,您可以回圈匹配和匹配的組以獲取客戶名稱:
' declare the pattern and input (escaping quotation marks) as well as a collection to store just the customer_name values
Dim pattern As String = "(?:"")(?<key>\w )(?:"":"")(?<value>((\w|\s|\.)) )(?:"",)"
Dim input As String = """Customer_name"":""JOHN DOE"",""Customer_id"":""9251954"",""Customer_team_id"":""HOST"",""Customer_position_id"":""MGR"",""Customer_short_name"":""Joey"",""Customer_eligibility"":""LT5"",""Customer_page_url"":""google.com"",""Customer_alt_id"":""M7"",""Customer_name"":""JANE DOE"",""Customer_id"":""8734817"",""Customer_team_id"":""HOST"",""Customer_position_id"":""TECH"",""Customer_name"":""JOSEPH DOE"",""Customer_id"":""8675307"""
Dim matches As MatchCollection = Regex.Matches(input, pattern)
Dim names As New List(Of String)()
' loop over each match
For Each match As Match In matches
' loop over each group in the match
For index As Integer = 0 To match.Groups.Count - 1
Dim group As Group = match.Groups.Item(index)
' only do something if we're on the "key" group, the "key" group's value is Customer_name, and there's at least one more group left
If (group.Name = "key" AndAlso group.Value = "Customer_name" AndAlso index < match.Groups.Count - 1)
' only do something if the next group is the "value" group
Dim valueGroup As Group = match.Groups.Item(index 1)
If (valueGroup.Name = "value") Then
' add the key's value
names.Add(valueGroup.Value)
Exit For
End If
End If
Next
Next
' set the TextBox's lines
TextBox4.Lines = names.ToArray()
小提琴:https ://dotnetfiddle.net/Zja46U
編輯 - 請記住,因為我們使用的是命名組,所以現在可以擴展此代碼以獲取任何鍵/值對。只是為了這個例子,我只得到Customer_name鍵/值對。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410499.html
標籤:
下一篇:Regex的使用。用模式替換
