Results 1 to 5 of 5

Thread: [RESOLVED] Get number out of a string

  1. #1

    Thread Starter
    Member
    Join Date
    Jan 2007
    Posts
    32

    Resolved [RESOLVED] Get number out of a string

    Hi there,

    as the title says i try to get a number out of a string.
    Like in:

    "3.1 Ram test"

    i try to get out the 3.1

    But the length of the number is not always the same. it could be like

    "3 Ram Test"
    "3.1 Ram Test"
    "3.11 Ram Test"

    etc.
    I thought there was something like val() but that doesnt work in vb.net.
    And the last thing is - there could b another number in that string, like

    "3.1 Ram Test 1"

    but i just want to have the 3.1

    Any suggestions??

    Thanx.
    Fred

  2. #2
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    Re: Get number out of a string

    Is there always a space between the number that you want and the first word?

    vb.net Code:
    1. Dim str As String = "3.11 Ram Test"
    2. Dim tmp() As String = str.Split(" "c)
    3. MessageBox.Show(tmp(0))

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Get number out of a string

    This is one of those cases where a Runtime function can add value:
    vb.net Code:
    1. Dim str As String = "3.11 Ram Test"
    2. Dim num As Double = Val(str)
    3.  
    4. MessageBox.Show(num.ToString())
    This will, of course, only work if the number is at the start of the string.
    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

  4. #4
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: Get number out of a string

    VB.NET Code:
    1. Imports System.Text.RegularExpressions
    2. ' ...
    3. MessageBox.Show((New Regex("((\d+)\.(\d+))")).Match("3.11 Ram Test").Value)

  5. #5

    Thread Starter
    Member
    Join Date
    Jan 2007
    Posts
    32

    Re: Get number out of a string

    Thanx for the answers.

    since the number will always be at the begining of the string jmcilhinneys method works perfect.
    But the others are also good to know.

    Fred

Posting Permissions

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



Click Here to Expand Forum to Full Width