【问题标题】:Need to separate out Letters from numbers in a string, via vb.net需要通过 vb.net 从字符串中的数字中分离出字母
【发布时间】:2016-11-04 09:21:32
【问题描述】:

我希望我的代码在字符串中找到字母旁边有数字的任何地方,并在两者之间插入一个空格。

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

123MainSt.Box123

应该是 123 Main St. Box 123

123百汇134

应该是: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

【问题讨论】:

  • 实际上,从您的示例来看,它看起来像是从字符串中的第二个字符开始,您只想在每个大写字母和每个不跟随另一个数字的数字前面放置一个空格。你可以用 for 循环做一些事情。
  • Rob,我更倾向于在字符串中的字母和数字放在一起的任何地方之间放置一个空格......
  • 你是老板 - 请参阅下面的答案
  • 在数字和数字之间插入空格的正则表达式方法仅仅是Regex.Replace(input, "(?&lt;=\d)(?=\p{L})|(?&lt;=\p{L})(?=\d)", " ")。有一种捕获组和匹配评估器的方法,但代码看起来很糟糕。但是,您上面的代码意味着您需要更具体的内容(例如忽略序数后缀等)。请澄清。
  • 另外,不要忘记接受对你有用的答案,并为那些有帮助的人点赞。

标签: regex vb.net excel visual-studio


【解决方案1】:

这是一个快速函数:

 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

【讨论】:

    【解决方案2】:

    我希望我的代码在字符串中找到字母旁边有数字的任何地方,并在两者之间插入一个空格。

    你可以使用的正则表达式是

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

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

    请注意,(?&lt;=\p{L}) 是一个正向lookbehind,需要在当前位置之前有一个字母, (?=\d)` 是一个正向lookahead,需要在当前位置之后有一个数字。这些是不使用文本的环视方法,因此您可以用 (= insert) 空格替换空格。

    【讨论】:

    • @Chrisetiquette 太好了,请考虑接受答案。
    猜你喜欢
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多