我有像TE_2015-2016_UnKnown,TE_2014-2015_UnKnown,TE_2013-2014_UnKnown
这样的字符串。我想在此字符串中获取整数数组(2015,2016,2014,2015,2013,2014)
。怎么做?
修改
我试试这个
Dim x As String = "TE_2015-2016_UnKnown,TE_2014-2015_UnKnown,TE_2013-2014_UnKnown"
Dim y As String = String.Empty
For Each xstr As String In x.Split(",")
y &= xstr.Split("_")(1).Replace("-", ",")
Next
Dim xarr() As Integer = Array.ConvertAll(y.Split(","), Function(str) Int32.Parse(str))
它的返回输出
(0): "2015"
(1): "20162014"
(2): "20152013"
(3): "2014"
但我想要
(0): "2015"
(1): "2016"
(2): "2014"
(3): "2015"
(4): "2013"
(5): "2014"
注意:TE
和Unknown
不是静态字符串。我给出了示例字符串。
答案 0 :(得分:0)
Split使用'_'和' - '然后选择可以解析的
Int32 value
String s = "TE_2015-2016_UnKnown,TE_2014-2015_UnKnown,TE_2013-2014_UnKnown"
s.Split(new ['-', '_']).Where(Function(w) Int32.TryParse(w, out value))
答案 1 :(得分:0)
这是使用正则表达式的方法:
Dim data As String = "TE_2015-2016_UnKnown,TE_2014-2015_UnKnown,TE_2013-2014_UnKnown"
Dim strNumbers As New List(Of String)
For Each m As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(data, "\d+")
strNumbers.Add(m.ToString)
Next
Dim numbers() As Integer = Array.ConvertAll(strNumbers.ToArray, Function(x) Int32.Parse(x))
For Each number As Integer In numbers
Debug.Print(number)
Next
编辑:不使用循环的另一种变体......
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim data As String = "TE_2015-2016_UnKnown,TE_2014-2015_UnKnown,TE_2013-2014_UnKnown"
Dim numbers = (From n In Regex.Matches(data, "\d+") Select Integer.Parse(n.value)).ToArray
For Each number As Integer In numbers
Debug.Print(number)
Next
End Sub
End Class