I am still very new to dotNET, and I have searched and searched, and racked my brain trying to figure this out.
I have a pattern as a string which looks like this :
3(a)-bab-4(c)-aab-7(d)-abab <---- pattern is always different and can be up to 50 or 60 characters
What I need is:
aaababccccaabdddddddabab
Can someone please help me figure this out?
Well, it looks like a RLE, split your string by '-', then check if contains '(', if so, take the number, extract the text and repeat in a loop
Dim sb As New StringBuilder()
Dim parts As String() = inputString.Split("-"C)
For Each part As String In parts
Dim indexOfPar As Integer = part.IndexOf("(")
If indexOfPar = -1 Then
sb.Append(part)
Else
Dim repeat As Integer = Integer.Parse(part.Substring(0, indexOfPar))
Dim toRepeat As String = part.Substring(indexOfPar, part.Length - (indexOfPar - 2))
'-2 to remove ()
For buc As Integer = 0 To repeat - 1
sb.Append(toRepeat)
Next
End If
Next
Return sb.ToString()
Here is a function that will work with the example that you gave. It is using String.Split and String.Replace to parse out your Data.
Module Module1
Sub Main()
Dim testValue As String = "3(a)-bab-4(c)-aab-7(d)-abab"
Console.WriteLine(testValue)
Console.WriteLine(ParseData(testValue))
Console.ReadLine()
End Sub
Public Function ParseData(value As String) As String
Dim temp As String = ""
Dim result As String = ""
Dim splitChar As Char() = {"-"c}
Dim split() As String = value.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
For Each section In split
If (IsNumeric(section(0))) Then 'Check to see if section starts with a number
Dim tmpvalue1() As String = section.Split(New Char() {"("c}) 'Check if section contains a paren
If tmpvalue1.Length > 0 Then 'If so then replace them and strip out the number to get to the repeating characters
Dim validChar As String = section.Replace("(", "").Replace(")", "").Replace(tmpvalue1(0), "")
Dim count As Integer
If Integer.TryParse(tmpvalue1(0), count) Then
temp = validChar
For x = 0 To count - 2
temp += validChar
Next
End If
End If
result += temp
Else
result += section
End If
Next
Return result
End Function
End Module
Result:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With