Results 1 to 4 of 4

Thread: [RESOLVED] Cut sting value under condition

  1. #1

    Thread Starter
    Addicted Member t3cho's Avatar
    Join Date
    Mar 2014
    Posts
    234

    Resolved [RESOLVED] Cut sting value under condition

    I have two string values.

    s1 = "This is my test value #2213 and its great"
    s2 = "This #ASD is my #Test value and number is #2215"

    The point is to pick up 4 digit number behind the # mark.

    With

    Code:
    _lItems.Add(item.Title.Substring(item.Title.IndexOf("#") + 1, 4))
    I can cut the string but but that is not correct. I need to scrap only 4 digit number behind # mark.

    How to make it

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Cut sting value under condition

    You could parse it yourself like this:-
    vbnet Code:
    1. '
    2.     Public Function GetNumber(ByVal s As String) As Integer
    3.  
    4.         Dim split As String() = s.Split("#"c)
    5.         Dim digits As New List(Of Char)
    6.  
    7.  
    8.         'Skip first string
    9.         For i = 1 To split.Count - 1
    10.             If Char.IsDigit(split(i).Chars(0)) Then
    11.                 For Each c As Char In split(i)
    12.                     If Char.IsDigit(c) Then
    13.                         digits.Add(c)
    14.                     Else
    15.  
    16.                         i = split.Count - 1
    17.  
    18.                     End If
    19.                 Next
    20.             End If
    21.  
    22.         Next
    23.  
    24.         Return CInt(New String(digits.ToArray))
    25.     End Function

    Usage:-
    vbnet Code:
    1. '
    2.         Dim s2 As String
    3.         Dim s1 As String
    4.  
    5.         s1 = "This is my test value #2213 and its great"
    6.         s2 = "This #ASD is my #Test value and number is #2215"
    7.  
    8.  
    9.         Debug.WriteLine(GetNumber(s1).ToString)
    10.         Debug.WriteLine(GetNumber(s2).ToString)

    Another way that's even better is to use regular expressions. Unfortunately, I haven't gotten around to learning them yet so I can't show that method but there are many members here who do know how to use them. You could wait for an answer from one of them or even study regular expressions yourself. Regular expressions would reduce all that code I posted to a single line.
    Last edited by Niya; Nov 19th, 2017 at 01:27 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,930

    Re: Cut sting value under condition

    If the number will always be 4 digits (and only one # character, which is always just before the number) then you can simplify it a lot:
    Code:
        Public Function GetNumber(ByVal s As String) As Integer
    
            Dim hashPosition As Integer = s.IndexOf("#"c)
    
            Dim numberText as String = s.subString(hashPosition + 1, 4)
    
            Return CInt(numberText)
        End Function
    ...or to make it more confusing (but not as much as a RegEx version), you could condense it down to one line:
    Code:
        Public Function GetNumber(ByVal s As String) As Integer
            Return CInt(s.subString(s.IndexOf("#"c) + 1, 4))
        End Function

  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Cut sting value under condition

    This is more or less the perfect job for a RegEx.

    If there can only be one per string and we're in a hurry:
    Code:
    Public Function ScrapeNumber(ByVal input As String) As String
        Dim regex As New Regex("#(\d{4})")
        Dim match As Match = regex.Match(input)
        If match.Success Then
            Return match.Groups(1)
        Else
            Return Nothing
        End If
    End Function
    (https://dotnetfiddle.net/77MUhe)

    I say "if we're in a hurry" becuase "return Nothing" is a very bad way to handle "there were no results", but it can be complex to decide how to better do things. Lately I favor either an Option(Of T) type or value tuples, but it doesn't matter because we have a better way. What if we return MULTIPLE?
    Code:
    Public Function ScrapeNumbers(ByVal input As String) As IEnumerable(Of String)
        Dim regex As New Regex("#(\d{4})")
        Dim numbers As New List(Of String)()
    
        For Each match In regex.Matches(input)
            If match.Success Then
                numbers.Add(match.Groups(1).Value)
            End If
        Next
    
        Return numbers
    End Function
    (https://dotnetfiddle.net/V7EXMy)

    Now "there are no results" is part of the contract of the function, so we don't have to mess with Nothing. I think that's probably a better way to approach it.

    It's always good to know the magic you're using, so here's what the RegEx "#(\d{4})" means:

    Match parts of the string that:
    • Start with a '#' character, then
    • 4 digits 0-9, stored in a matching group.
    The way we get the digits is to check the Groups property after verifying the match succeeded. Groups(0) is always "the entire match", so Groups(1) is the one we want.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

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