Regex on VB.Net to get only first few numbers from left to right
I am pretty new on regular expressions, but as far as I've been wandering around Google, the only thing I could do to solve 开发者_JS百科my problem is through regex.
I have a collection of strings which have patterns like these:
"3 - Orange, Lemon"
"4 - Pineapple, Orange" "12 - Lime, Strawberry"My current code is:
Private Sub cmbKelas_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbKelas.SelectedIndexChanged
LblID.Text = cmbKelas.Text
End Sub
Which gives output to entire string.. what I wanted is that cmbKelas.Text will have its value stripped so each string will changes into:
"3"
"4" "12"Only the first few numbers. A comment, suggestion, or point to the right links/articles would help because so far I couldn't manage to find a decent tutorials that easy to understand.
Regex is overkill for this task.
You can use the IndexOf
method to figure out where the first space occurs and then use the Substring
method to take the beginning of the string up to the index of the first space.
Dim values As String() = New String() { _
"3 - Orange, Lemon", _
"4 - Pineapple, Orange", _
"12 - Lime, Strawberry" _
}
For Each input as String In values
Dim number As String = input.Substring(0, input.IndexOf(" "))
Console.WriteLine(number)
Next
Alternately, you could use the Split
method to split on spaces and take the first item in the split result array as follows:
For Each input as String In values
Dim split As String() = input.Split(" "c)
Dim number As String = split(0)
Console.WriteLine(number)
Next
If you want to do this with Regular Expressions you could use something like this:
Dim ResultString As String
ResultString = Regex.Match(SubjectString, "^\d+").Value
Where SubjectString would be the string you are searching in.
Explanation (since you are new to regex):
- The
^
signifies the beginning of a string (that why you don't match number that are not at the beginning) \d
signifies a digit 0-9 (it's the short form of [0-9] which would do the same)- and
+
means that the character prior to+
will be matched at least once.
That way you will match 1 to infinite digits at the beginning of the string.
As an alternative to SubString
, you could use Split
:
Dim numbers = new List(Of String)()
For Each input as String In values
Dim parts = input.Split(New Char() {" "c})
If (parts.Length > 0) Then
numbers.Add(parts[0])
End If
Next
精彩评论