【问题标题】:Parsing years from strings从字符串中解析年份
【发布时间】:2012-11-18 18:02:52
【问题描述】:

我有 12-13 个字符串,例如

  • FVS1012 09 GO5
  • OCGG 85 0827KU9

根据长度我必须得到 bold 部分,表示年份,在示例中为 2009 年和 1985 年。

如何获得“年”?

Dim str As String
Dim ResultStr As String
str = "FVS101209GO5"
Dim number As Integer = str.Length()
Select Case number
    Case 12
        ResultStr = str.Substring(8, 12)
        ResultStr = ResultStr.Substring(1, ResultStr.Length() )
    Case 13
        ResultStr = str.Substring(5, 13)
        ResultStr = ResultStr.Substring(1, ResultStr.Length() )
    Case Else
        Debug.WriteLine("other")
End Select

还有其他更好的方法吗?

【问题讨论】:

  • 从字符串的外观来看,除了扫描“没有字母数字字符的数字序列”之外,我没有看到任何可以轻松识别的模式。在不了解字符串格式的情况下,我怀疑这会导致“更好”的解决方案,只是一个不同的解决方案。
  • 如果这一年总是独立的(并且是唯一一个这样做的)这个正则表达式会做到这一点:\b(\d{2})\b
  • 如何在代码中实现它?

标签: string parsing substring vb.net-2010


【解决方案1】:

你可能会这样做............

Select Case number
  Case 12
    ResultStr = mid(str, 8 ,2)
  Case 13
    ResultStr = mid(str, 5, 2)
  Case Else
    Debug.WriteLine("other")
End Select

请注意,每个 case 语句只保存一行,所以是否值得这样做?我不确定

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2021-04-16
    • 2012-03-04
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多