【问题标题】:Get substring until first numeric character获取子字符串直到第一个数字字符
【发布时间】:2014-03-04 12:39:06
【问题描述】:

就像我已经解释过的标题一样,我想获得一个字符串的子字符串(其中包含一个地址),并且我只想拥有街道..

不可能只取文本(非数字)字符,因为这样该框将保留。 在第一个空格之前不能使用子字符串,因为街道名称可以包含空格..

例如 'developerstreet 123a' -> 想要拥有 'developerstreet' 'a' 是房子的箱号,我不感兴趣..

如何在 VB.NET 中做到这一点?

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    解析地址是出了名的困难,所以我提醒您确保您在做出选择时非常慎重。我强烈建议您查看邮政服务提供的文件。如果这些是美国地址,您应该先查看USPS Publication 28

    但是,要回答您的具体问题,您可以使用Char.IsDigit 方法查找字符串中第一个数字字符的索引。您可能还想看看Char.IsNumber 方法,但这可能比您真正想要的更具包容性。例如,这将获取input 字符串中第一个数字字符的索引:

    Dim index As Integer = -1
    For i As Integer = 0 to input.Length - 1
        If Char.IsDigit(input(i)) Then
            index = i
            Exit For
        End If
    Next
    

    但是,对于像这样的复杂字符串解析,我建议学习正则表达式。使用RegEx,获取字符串开头的非数字部分变得微不足道:

    Dim m As Match = Regex.Match(input, "^\D+")
    If m.Success Then
        Dim nonNumericPart As String = m.Value
    End If
    

    上例中正则表达式的含义如下:

    • ^ - 匹配的字符串必须从行首开始
    • \D - 任何非数字字符
    • + - 一次或多次

    【讨论】:

      【解决方案2】:

      试试这个:

          Private Sub MyFormLoad(sender As Object, e As EventArgs) Handles Me.Load
      
           Dim str As String = "developerstreet 123a"
                  Dim index As Integer = GetIndexOfNumber(str)
                  Dim substr As String = str.Substring(0, index)
                  MsgBox(substr)
          End Sub
      
      
      
             Public Function GetIndexOfNumber(ByVal str As String)
                  For n = 0 To str.Length - 1
                      If IsNumeric(str.Substring(n, 1)) Then
                          Return n
                      End If
                  Next
                  Return -1
              End Function
      

      输出将是:developerstreet

      【讨论】:

        【解决方案3】:
        text.Substring(0, text.IndexOfAny("0123456789"))
        

        【讨论】:

        • 欢迎来到 Stack Overflow!虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的回答添加解释并说明适用的限制和假设。
        猜你喜欢
        • 2020-02-12
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 2015-02-02
        • 2021-04-15
        • 2014-01-04
        • 2012-01-05
        • 2010-12-28
        相关资源
        最近更新 更多