在visual basic中拆分字符串

Bry*_*ord 0 regex vb.net string vba

我有一个从文件导入的多个字符串.字符串的格式如下:

Smith, Tom 1/2/62 45484

[Last Name], [First Name] [Date] [Number]
Run Code Online (Sandbox Code Playgroud)

我需要一种方法将这些分成四个变量.

Dim first_name as string = first name

我以为我可以使用正则表达式,但我一直在用它打墙.

谢谢你的帮助!

Ste*_*art 5

是的,RegEx是一个很好的选择.这是你在VB中如何做到这一点:

Dim input As String = "Smith, Tom 1/2/62 45484"
Dim pattern As String = "(?<last>.*?), (?<first>.*?) (?<date>\S+) (?<number>\d+)"
For Each m As Match In Regex.Matches(input, pattern)
    Dim last As String = m.Groups("last").Value
    Dim first As String = m.Groups("first").Value
    Dim [date] As String = m.Groups("date").Value
    Dim number As String = m.Groups("number").Value
Next
Run Code Online (Sandbox Code Playgroud)

您可能需要调整模式以满足您的需求.这是我演示的模式的含义:

  • (?<last>.*?) - 捕获字符串的姓氏部分
    • ( - 开始一个捕获组
    • ?<last> - 为捕获组提供名称
    • . - 任何角色
    • *? - 任意次数(任意长度的字符),非贪婪.放置?之后*是什么使它不贪婪.非贪婪只是意味着它将捕获尽可能少的字符串(即只到第一个逗号而不是直到最后一个逗号)
    • ) - 结束捕获组
  • , - 必须有逗号后跟名字和姓氏之间的空格
  • (?<first>.*?) - 捕获名字. .*?捕获任何长度的任何字符,非贪婪.
  • - There must be a single space between the first name and the date
  • (?<date>\S+) - 截取日期. \S+捕获一个或多个非空白字符.
  • - There must be a single space between the date and the number
  • (?<number>\d+) - 捕获号码. \d+捕获一个或多个数字字符.

我使用命名组,以便代码更清晰,更易读.您也可以使用编号组并通过索引(例如m.Groups(0).Value)读取它们.

此外,我使用循环来查看来自的所有结果Matches.但是,如果您只是一次给RegEx一行,或类似的东西,其中输入只能包含一个匹配,那么您可以使用该Match方法,这更容易:

Dim m As Match = Regex.Match(input, pattern)
If m.Success Then
    Dim last As String = m.Groups("last").Value
    Dim first As String = m.Groups("first").Value
    Dim [date] As String = m.Groups("date").Value
    Dim number As String = m.Groups("number").Value
End If
Run Code Online (Sandbox Code Playgroud)