需要通过vb.net将字母中的数字与字母串分开

时间:2016-07-01 21:50:28

标签: regex vb.net excel visual-studio

我希望我的代码可以在字符串中找到字母旁边有数字的位置,并在两者之间插入一个空格。

我有几个没有空格的地址,我需要通过从字母中分出数字来插入空格。例如:

123MainSt.Box123

应该是123 Main St. Box 123

123Parkway134

应该是:123 Parkway 134

这是我从我的代码开始的地方,但它在开头梳理两个数字....

Dim Digits() As String = Regex.Split(Address, "[^0-9]+")
        'MsgBox(Digits.Count)
        If Digits.Length > 2 Then

            ' For Each item As String In Digits

            Dim Letters As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")

            rCell.Value = Digits(0) & Letters & Digits(1)

        End If

        If Digits.Length < 3 Then
            If Address.Contains("th") Then
            Else

                Dim Part1 As String = Regex.Replace(Address, "[^0-9]+", "")
                Dim Part2 As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")
                'MsgBox(Part1 & " " & Part2)
                rCell.Value = Part1 & " " & Part2
            End If
        End If

2 个答案:

答案 0 :(得分:1)

  

我希望我的代码可以在字符串中找到字母旁边有数字的位置,并在两者之间插入一个空格。

您可能使用的正则表达式是

Regex.Replace(input, "(?<=\d)(?=\p{L})|(?<=\p{L})(?=\d)", " ")

第一个选择 - (?<=\d)(?=\p{L}) - 匹配数字和字母之间的位置,第二个选项 - (?<=\p{L})(?=\d) - 匹配字母和数字之间的位置。

请注意,(?<=\p{L})是一个积极的外观,需要在当前位置之前写一个字母,而 (?= \ d)`是一个正向前瞻,需要在当前位置之后有一个数字。这些是不消耗文本的外观,因此用(= insert)空格替换空格。

答案 1 :(得分:0)

这是一个快速的功能:

 Private Function AddSpaces(ByVal input As String) As String

    If input.Length < 2 Then Return input

    Dim ReturnValue As String = String.Empty
    Dim CurrentChar, NextChar As String

    For x As Integer = 1 To input.Length

        CurrentChar = Mid(input, x, 1)
        NextChar = Mid(input, x + 1, 1)

        ReturnValue &= CurrentChar

        If (IsNumeric(CurrentChar) AndAlso (Not IsNumeric(NextChar))) OrElse
           ((Not IsNumeric(CurrentChar)) AndAlso IsNumeric(NextChar)) Then
            ReturnValue &= " "
        End If

    Next

    Return ReturnValue

End Function