I am trying to use regular expressions to search a string for decimal values. I want to convert the matches collection to a decimal array. I then want to sort the decimal array and add the lowest decimal value to a textbox using VB.NET. Is this possible?
Asked
Active
Viewed 410 times
-2
-
donno about VB syntax but isnt it simple to do with a foreach loop? – Steve Jan 21 '15 at 23:55
-
Yes, it is possible. Have you tried anything? – Mark Jan 22 '15 at 00:04
-
I have tried the following code: dim regex as system.text.regularexpressions.regex = New system.text.regularexpressions.regex("regex code") Dim match As Match Collection = regex.Matches(TextBox1.Text) match.toarry(matchArray) – Joseph Finley Jan 22 '15 at 00:49
-
I have tried the following code: dim regex as system.text.regularexpressions.regex = New system.text.regularexpressions.regex("regex code") Dim match As Match Collection = regex.Matches(TextBox1.Text) then I get lost ...... but here is a guide of what I am trying to do match.Convert.ToDecimal(match) match.toarry(matchArray) Array.Sort(matchArray) matchArray(0) = TextBox2.Text – Joseph Finley Jan 22 '15 at 00:57
1 Answers
0
Not sure what sort of values you are looking for in your string, but using the regex from this answer, you could do something like the following:
Dim str = "1.23 ds -100.2 xyz 97.5 1.22 .1"
Dim minVal = Regex.Matches(str, "[+-]?((\d+(\.\d*)?)|(\.\d+))") _
.Cast(Of Match)() _
.Select(Function(x) CDec(x.Value)) _
.Min()
Debug.WriteLine(minVal)
Which will print -100.2
.
The Cast(Of Match)()
function lets you use the LINQ extension methods on the matches to convert the matched values to decimal using Select
and then find the minimum value using Min
.
You can then use minVal
to set your TextBox
.