PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2017 Find leading integers in a string-VBForums
Results 1 to 23 of 23

Thread: Find leading integers in a string

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2006
    Posts
    280

    Find leading integers in a string

    I need to check for the first 1 , 2, or 3 numbers in a line of text. I need to use the for a DB search.
    I started to do a for next loop but was unsure how to count only numbers of the text.
    The numbers I need are always at the beginning of the text file.

    Code:
     Dim X As Integer
    
            For X = 1 To Len(TextBox1.Text)
    
            Next
    Thanks

  2. #2
    Fanatic Member
    Join Date
    Sep 2017
    Posts
    644

    Re: Find leading integers in a string

    cant a digit value only exist within the first 3 chars?

  3. #3
    Lively Member
    Join Date
    Jan 2016
    Posts
    78

    Re: Find leading integers in a string

    Code:
    if IsNumeric(TextBox1.Text.Substring(0,3)) then
    'number is 3 digits
    elseif IsNumeric(TextBox1.Text.Substring(0,2)) then
    'number is 2 digits
    elseif IsNumeric(TextBox1.Text.Substring(0,1)) then
    'number is 1 digit
    else
    'not a number
    end if
    If the numbers are always at the start, would that work?

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2006
    Posts
    280

    Re: Find leading integers in a string

    Sorry but no matter whether one number is present or 3 numbers are present I only show the first statement as true

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2006
    Posts
    280

    Re: Find leading integers in a string

    The text comes from a Combobox with two fields concatenated together so yes the will ALWAYS be a least one number then a space and the text. I need to separate the number for other use in my program.

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Dec 2006
    Posts
    280

    Re: Find leading integers in a string

    Is there a way to count from left to right and find the first space and then subtract the from the total to find out how many characters are numeric and go from there?

  7. #7
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,199

    Re: Find leading integers in a string

    You can use .IndexOf , eg:
    Code:
    Dim firstSpacePosition = TextBox1.Text.IndexOf(" ")

  8. #8
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    40,199

    Re: Find leading integers in a string

    You can use .IndexOf , eg:
    Code:
    Dim firstSpacePosition = TextBox1.Text.IndexOf(" ")

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,497

    Re: Find leading integers in a string

    There aren't so many uses for it, but look into Val(), as it may be ideal for this problem. What Val() does is starts parsing the string converting characters into numbers. It quits as soon as it finds a character that is NOT a number, including spaces. So, if you number starts with 5 then a space:

    Val("5 something") = 5
    Val("64 Something") = 64

    and so on. However, Val() will return a Double, so you need to cast that to Integer:
    Code:
    Dim yourNumber = CInt(Val(yourString))
    My usual boring signature: Nothing

  10. #10
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,018

    Re: Find leading integers in a string

    1. You can call the TakeWhile extension method to take items from the head of a list while they match a specific condition.
    2. You can call the Take extension method to take up to a maximum number of items from the head of a list.
    3. A String is an enumerable list of Char.

    Putting those things together, you can get a String containing up to three digits from the head of another String like this:
    vb.net Code:
    1. Public Function GetLeadingDigits(text As String, count As Integer) As String
    2.     Return New String(text.TakeWhile(Function(ch) Char.IsDigit(ch)).
    3.                            Take(count).
    4.                            ToArray())
    5. End Function
    Example usage:
    vb.net Code:
    1. Console.WriteLine(GetLeadingDigits(String.Empty, 3))
    2. Console.WriteLine(GetLeadingDigits("Hello World", 3))
    3. Console.WriteLine(GetLeadingDigits("1Hello World", 3))
    4. Console.WriteLine(GetLeadingDigits("123Hello World", 3))
    5. Console.WriteLine(GetLeadingDigits("12345Hello World", 3))
    Output:


    1
    123
    123
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  11. #11
    Fanatic Member
    Join Date
    Sep 2017
    Posts
    644

    Re: Find leading integers in a string

    Was trying to post from my phone earlier but couldn't get it to submit. I was thinking something simple like so:
    Code:
        Private Sub ButtonIntFromStr_Click(sender As Object, e As EventArgs) Handles ButtonIntFromStr.Click
            Dim SourceString As String = "12345fregvretbtrbt"
            Dim IntString As String = String.Empty
            Dim TargetInt As Integer = Nothing
            For Each Chr As Char In SourceString.Substring(0, 3)
                If Char.IsDigit(Chr) Then
                    IntString &= Chr.ToString
                End If
            Next
            TargetInt = CInt(IntString)
         
        End Sub
    John, I love seeing the thing you come up with.

  12. #12
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,018

    Re: Find leading integers in a string

    Quote Originally Posted by kpmc View Post
    Was trying to post from my phone earlier but couldn't get it to submit. I was thinking something simple like so:
    Code:
        Private Sub ButtonIntFromStr_Click(sender As Object, e As EventArgs) Handles ButtonIntFromStr.Click
            Dim SourceString As String = "12345fregvretbtrbt"
            Dim IntString As String = String.Empty
            Dim TargetInt As Integer = Nothing
            For Each Chr As Char In SourceString.Substring(0, 3)
                If Char.IsDigit(Chr) Then
                    IntString &= Chr.ToString
                End If
            Next
            TargetInt = CInt(IntString)
         
        End Sub
    John, I love seeing the thing you come up with.
    I was assuming that the OP would want to stop when they found a non-digit, which may or may not be the case. For an input of "1X1YZ" my code would produce "1" while yours would produce "11". If I am correct in my assumption then you'd need to change your code to add an exit condition:
    Code:
    If Char.IsDigit(Chr) Then
        IntString &= Chr.ToString
    Else
        Exit For
    End If
    If I'm wrong in my assumption then my code could be changed to this:
    vb.net Code:
    1. Public Function GetLeadingDigits(text As String, count As Integer) As String
    2.     Return New String(text.Take(count).
    3.                            Where(Function(ch) Char.IsDigit(ch)).
    4.                            ToArray())
    5. End Function
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  13. #13
    Fanatic Member
    Join Date
    Sep 2017
    Posts
    644

    Re: Find leading integers in a string

    I was assuming that the OP would want to stop when they found a non-digit
    Nice observation.

  14. #14
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,497

    Re: Find leading integers in a string

    That's why I suggested Val(), as it will do just that. I can't say that I see the point in writing your own function, or using extensions, when there is a built in function that does the work. There aren't many uses for Val(), why overlook the one use it has?
    My usual boring signature: Nothing

  15. #15
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,018

    Re: Find leading integers in a string

    Quote Originally Posted by Shaggy Hiker View Post
    That's why I suggested Val(), as it will do just that. I can't say that I see the point in writing your own function, or using extensions, when there is a built in function that does the work. There aren't many uses for Val(), why overlook the one use it has?
    The code you posted has issues with regards to the stated requirements. Firstly, it doesn't respect the three-character limit. If you passed in "1234Hello" then you'd get 1234 back, so not what's required. You'd have to add a Substring call for that at least. Also, Val converts to ANY Double value. What results would your code produce if it was passed "1.6Hello" or "-12Hello" and would they be what was actually expected based on the requirements? Obviously whether that's an issue depends on what the possible inputs are but if you can easily write code that will provide the expected output no matter the input, I'd go with that.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,497

    Re: Find leading integers in a string

    My interpretation comes from post #5. If you concatenate a number to the front of a string to build some display value, then want to strip the numbers off, then Val() will do the whole job for all cases other than those where the second part of the concatenation begins with a number. However, post #5, and #6 tell us that the format is "number space whatever". That space will stop Val(), so Val() will get the correct number from the beginning of these particular strings as long as the format is the format that was described. The function solves a larger case where the format is largely "any string where up to the first three characters might be numbers." That's nice, but it's not the problem as described.
    My usual boring signature: Nothing

  17. #17
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    100,018

    Re: Find leading integers in a string

    Quote Originally Posted by Shaggy Hiker View Post
    That's nice, but it's not the problem as described.
    Fair point. Not sure I read post #5 previously.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  18. #18
    Frenzied Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    1,280

    Re: Find leading integers in a string

    Hi,

    regex would be an option

    Code:
     Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            TextBox1.Text = "1123 aBc"
        End Sub
    
        Public Function Reformat(ByVal str As String) As String
            Return System.Text.RegularExpressions.Regex.Replace(str, "([a-zA-Z]+)", "")
        End Function
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TextBox2.Text = Reformat(TextBox1.Text)
        End Sub
    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  19. #19
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    32,497

    Re: Find leading integers in a string

    I was thinking a bit more about this after the discussion with John. I don't think anybody has pointed this out yet, but the problem shouldn't be arising in the first place. Post #5 tells us that the string comes from a ComboBox where a number is concatenated onto a space and a string. We've all seen plenty of examples of something like this:

    1 Introduction
    2 First Chapter
    ...etc.

    and any number of other examples. However, from the first post, we see the reason for getting the number off the string is to use as a reference to a database. Essentially, the string is a display member that incorporates the value member. Far better would be to have some kind of key value arrangement (quite likely a datatable, really) and bind the combobox to it. Then there would be no need to mess with the string at all, because the value would exist in a different column of the source table. That could be set up with the DisplayMember being the field that held the full, concatenated string, while the ValueMember is the number alone. To go a step further (or is it farther?), assuming that this data comes from the database in the first place, a query would build that datatable in a single step.
    My usual boring signature: Nothing

  20. #20
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,471

    Re: Find leading integers in a string

    I see that there has been a lot of discussion on this already, but for what it is worth here is a solution that I provided in the VB.NET codebank: http://www.vbforums.com/showthread.p...ring-to-Double essentially it returns the numbers contained at the beginning of a String using the current culture to validate unary operators and mantissa. If you only want to match Integers and not Doubles, you can remove the If/Then block that proceeds the comment:
    'Optionally match an exponent, followed by an optional unary operator, followed by 1 or more digits

  21. #21
    Frenzied Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    1,280

    Re: Find leading integers in a string

    Hi,

    I think Shaggy could be right, a Datatable should be the best solution.

    I tried another way the Data (numbers) may appear

    Code:
     Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            TextBox1.Text = "1.235,678.10 aBc 13"
        End Sub
    
        Public Function Reformat1(ByVal str As String) As String
            Return System.Text.RegularExpressions.Regex.Match(str, "^\d+(?:[.,]\d+)*").Value
            'or 
            'Return System.Text.RegularExpressions.Regex.Match(str, "^\d+").Value
            'but this would just return 1
    
    
        End Function
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TextBox2.Text = Reformat1(TextBox1.Text)
        End Sub
    this will return the first number , ignore the Text and ignore the last number

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  22. #22
    Fanatic Member
    Join Date
    Sep 2017
    Posts
    644

    Re: Find leading integers in a string

    If we are going to kick this around some more, we may as well add every possible solution. The OP said there is a #, a space, and a string, so as the SelectedINdexChanged of his combo he could Split the string into an array and use the first element for his lookup. You can force the length into 2 substrings so it wouldn't create an element per space, only on the first space.

    Code:
    Dim Result() As String = Combobox.Text.Split(New Char() {" "c}, 2)
    Dim TargetInt As Integer = CInt(Result(0))

  23. #23
    Frenzied Member ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    1,280

    Re: Find leading integers in a string

    Quote Originally Posted by kpmc View Post
    If we are going to kick this around some more, we may as well add every possible solution. The OP said there is a #, a space, and a string, so as the SelectedINdexChanged of his combo he could Split the string into an array and use the first element for his lookup. You can force the length into 2 substrings so it wouldn't create an element per space, only on the first space.

    Code:
    Dim Result() As String = Combobox.Text.Split(New Char() {" "c}, 2)
    Dim TargetInt As Integer = CInt(Result(0))
    that's clever kpmc, me using regex is probably an overkill

    regards
    Chris
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width