substring from a string

ar_pad

Active member
Joined
Jun 5, 2006
Messages
26
Programming Experience
Beginner
Hi,

Can anyone show me the simplest way to retrive the data between #1 from the given string.

#1XYZXYZ#1#2UVWUVW#2#1AAABBBED#1#1SSSSWDWD#1

Result will be like XYZXYZAAABBBEDSSSSWDWD

Note: String is variable. Generated at runtime. Need to look two "#1" and extract data between them.

Thank You!
 
VB.NET:
Sub Main()
        Dim str As String = "#1XYZXYZ#1#2UVWUVW#2#1AAABBBED#1#1SSSSWDWD#1"
        Dim spl As String() = str.Split("#")
        Dim sb As New Text.StringBuilder
        For Each s As String In spl
            If Not s.StartsWith("2") Then
                sb.Append(s.Trim("1"))
            End If
        Next

        Console.WriteLine(sb.ToString)
        Console.WriteLine("Is correct result: " & sb.ToString.Equals("XYZXYZAAABBBEDSSSSWDWD"))
        Console.ReadLine()
    End Sub
 
Here is one using regular expressions:
VB.NET:
'Imports System.Text 
Sub regex()
 Dim file As String = "#1XYZXYZ#1#2UVWUVW#2#1AAABBBED#1#1SSSSWDWD#1"
 Dim ex As String = "#1.*?#1"
 Dim rm As RegularExpressions.MatchCollection = _
       RegularExpressions.Regex.Matches(file, ex)
 'displaying the results
 Dim out As New StringBuilder
 Dim mstr As String
 For i As Short = 0 To rm.Count - 1
  mstr = rm.Item(i).Value
  out.Append(mstr.Substring(2, mstr.Length - 4))
 Next
 MessageBox.Show(out.ToString)
End Sub
 
Back
Top