VB.Net Split A Group Of Text - string

I am looking to split up multiple lines of text to single them out, for example:
Url/Host:ftp://server.com/1
Login:Admin1
Password:Password1
Url/Host:ftp://server.com/2
Login:Admin2
Password:Password2
Url/Host:ftp://server.com/3
Login:Admin3
Password:Password3
How can I split each section into a different textbox, so that section one would be put into TextBox1.Text on its own:
Url/Host:ftp://server.com/1
Login:Admin1
Password:Password1

If that's the exact format you could just split it on two newlines in a row:
Dim text As String ' your text
Dim sep() As String = {vbNewLine & vbNewLine}
Dim sections() As String = text.Split(sep, StringSplitOptions.None)
and then just loop through them and put one value in each Textbox.

Related

VB.net Trim function

I have an issue with trim the string method NOT working completely I have reviewed MS Docs and looked of forums but with no luck... It's probably something simple or some other parameter is missing. This is just a sample,
Please note I need to pick up text before and after #, hence than I was planning to use # as a separator. Trim start # #, Trim End # #. I can't use The last Index or Replace per my understanding they have no direction. But perhaps I am misunderstood MS docs regards to trim Start and End as well...
thanks!
Dim str As String = "this is a #string"
Dim ext As String = str.TrimEnd("#")
MsgBox(ext)
ANSWER:
I found a solution for my problem, if you experience similar please see below:
1st: Trim end will NOT scan for the "character" from the Right as I originally thought it will just remove it from the right.... A weak function I would say:). IndexOf direction ID would be a very simple and helpful. Regards My answer was answered by Andrew, thanks!
Now there is another way around it if you try to split a SINGLE String INTO - QTY based on CHARACTER separation and populate fields accordingly.
Answer is ArrayList. Array List will ID each String so you can avoid repeated populations and etc. After you can use CASE or IF to populate accordingly.
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating
Case 1 '1st string(split)
MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).
Case 2 '2nd string(split)
MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
End Select
index += 1 'Here we adding one shift thru strings as we go
Next
Rather than:
Dim str As String = "this is a #string"
Dim ext As String = str.TrimEnd("#")
Try:
Dim str As String = "this is a #string"
Dim ext As String = str.Replace("#", "")
Dim str As String = "this is a #string"
Dim parts = str.Split("#"c)
For Each part in parts
Console.WriteLine($"|{part}|")
Next
Output:
|this is a |
|string|
Maybe there is a better way as we know there are multiple things to do the same thing.
The solution I used is below:
Dim arrList As New ArrayList("this is a # string".Split("#"c)) ' Will build the list of your strings
Dim index As Integer = 1 ' this will help us index the strings 1st, 2nd and etc.
For Each part In arrList 'here we are going thru the list
Select Case index ' Here we are identifying which field we are populating
Case 1 '1st string(split)
MsgBox("1 " & arrList(0) & index) '1st string value left to SPLIT arrList(0).
Case 2 '2nd string(split)
MsgBox("2 " & arrList(1) & index) '2nd string value left to SPLIT arrList(1).
End Select
index += 1 'Here we adding one shift thru strings as we go
Next

Indent a string by 4 spaces (Add Tab to string)

I am trying to add indentation to a string, essentially adding 4 spaces in front of each line in the string. The string that I want to add the indentation to is called StringToIndent.
Public Class ModifyPage
Private Sub Button_Test_Click(sender As Object, e As RoutedEventArgs) Handles Button_Test.Click
Dim StringToIndent As String = ("This is the first row
This is the second row
This is the third and final row in MyString")
Dim MySecondString As String = "This is a string in one line."
Dim BothStringsTogether = StringToIndent & Environment.NewLine & MySecondString
Debug.Write(BothStringsTogether)
End Sub
End Class
The current output:
This is the first row
This is the second row
This is the third and final row in MyString
This is a string in one line.
I want the final code (that is indented) to output:
This is the first row
This is the second row
This is the third and final row in MyString
This is a string in one line.
How can this be achieved through code? Is there a formatting option that allows me to add indentation? A method that doesn't require me to loop through a string and adding four spaces for each line would be preferable.
Edit: A way to achieve the expected output is to replace the new line with a new line and then add the indent. However, there must be a more elegant way of doing it?
Code:
Dim StringToIndent As String = ("This is the first row
This is the second row
This is the third and final row in MyString")
Dim indentAmount = 4
Dim indent = New String(" "c, indentAmount)
StringToIndent = indent & StringToIndent.Replace(Environment.NewLine, Environment.NewLine & indent)
Debug.Write(StringToIndent)
Maybe something like:
Dim res as String
Dim parts As String() = StringToIndent.Split(ControlChars.CrLf.ToCharArray)
For Each part As String In parts
res.Append(" ") & part & vbCrLf
Next
In C# you can mark the String as a verbatim string literal by prefixing the literal with the # symbol.
In VB.NET we don't have this option. Instead, a workaround would be to create an XML literal and get the value. Here is an example:
Dim input As String = <element> This is the first row
This is the second row
This is the third and final row in MyString
This is a string in one line.
</element>.Value().ToString()
Debugger.WriteLine(input.ToString())
If the value is not static, e.g. you're getting it from somewhere, then you're forced to iterate through the String in some form. You can either Replace like in your example, do a Split and Join (similar to your example), or you'll need to manually iterate.
The manual iteration could look more elegant using LINQ, but you don't gain anything from it.
The bottom line is that if your String is static then you can use the XML literal example I provided, otherwise if the String is dynamic then your solution is perfectly appropriate.
UPDATE
As Andrew Morton pointed out, multiple line String literals have existed since Visual Studio 2017. The following would produce the same outcome as my XML literal example:
Dim input As String = " This is the first row
This is the second row
This is a string in one line"
Debugger.WriteLine(input)
Using an interpolated string indicated by the $ preceeding the string and the vb constants.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s = $"{vbTab}This Is the first row{vbCrLf}{vbTab}This Is the second row{vbCrLf}{vbTab}{vbTab}This Is the third And final row in MyString{vbCrLf}This Is a string in one line."
Debug.Print(s)
End Sub

Finding multiple instance of a variable length string in a string

I'm trying to extract my parameters from my SQL query to build my xml for an SSRS report. I want to be able to copy/paste my SQL into Excel, look through the code and find all instances of '#' and the appropriate parameter attached to it. These paramaters will ultimately be copied and pasted to another sheet for further use. So for example:
where DateField between #FromDate and #ToDate
and (BalanceFiled between #BalanceFrom and #BalanceTo
OR BalancdField = #BalanceFrom)
I know I can use Instr to find the starting position of the first '#' in a line but how then do I go about extracting the rest of the parameter name (which varies) and also, in the first two lines of the example, finding the second parameter and extracting it's variable lenght? I've also tried using the .Find method which I've been able to copy the whole line over but not just the parameters.
I might approach this problem like so:
Remove characters that are not surrounded by spaces, but do not
belong. In your example, the parentheses need to be removed.
Split the text using the space as a delimiter.
For each element in the split array, check the first character.
If it is "#", then the parameter is found, and it is the entire value in that part of the array.
My user-defined function looks something like this:
Public Function GetParameters(ByRef rsSQL As String) As String
Dim sWords() As String
Dim s As Variant
Dim sResult As String
'remove parentheses and split at space
sWords = Split(Replace(Replace(rsSQL, ")", ""), "(", ""), " ")
'find parameters
For Each s In sWords
If Left$(s, 1) = "#" Then
sResult = sResult & s & ", "
End If
Next s
'remove extra comma from list
If sResult <> "" Then
sResult = Left$(sResult, Len(sResult) - 2)
End If
GetParameters = sResult
End Function

save csv as pipe delimited using vba

I have a csv file which has data as shown below:
PPIC,11/20/2013 10:23,11431,10963,,Tremors ,
PPIC,11/20/2013 10:23,11431,11592,,"Glioblastoma, Barin ",
the key difference is that row 1 contains a single word (last column), whereas the second row contains data enclosed in double quotes (but comma separated)
This is causing my BULK Import routine to import data wrong for second row. when BULK IMPORT runs, it splits the second row into multiple columns.
I read lots of posts on StackOverflow, and lots of suggestions point out to have a "pipe" delimited file as the input for bulk insert, that will remove any inconsistencies with the quoted text.
How can I convert this comma separated file into a pipe delimited file using a vb excel macro? I want to keep the process automated (where it will take the input csv file, convert it to pipe delimited and then send the file further for importing).
OR
How can I address the inconsistent quotes to be used whilst doing a BULK Insert?
Any thoughts / help appreciated.
This would do it:
Sub MySub()
Dim FileString As String
Dim Pattern As String
Dim ReplacementPattern As String
Dim ChangedStr As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
FileString = "PPIC,11/20/2013 10:23,11431,10963,,Tremors ," & vbCrLf & "PPIC,11/20/2013 10:23,11431,11592,,""Glioblastoma, Barin "","
Pattern = "(""[^""]*""|[^"",]*)?,"
ReplacementPattern = "$1|"
RE.Pattern = Pattern
RE.Global = True
RE.MultiLine = True
ChangedStr = RE.Replace(mystr, ReplacementPattern)
End Sub
Hope this does the trick

Replace String Two Different Parts

I am extracting a column of data from a range of filenames. All my filenames are strings in the form:
Temporary PSD Report 'Month' 2011.xls
I am using Replace to extract the month from each, at the moment I am doing it in two stages which works but it seems a bit clumsy. Is there a way to use some kind of AND for multiple replacements in the same string?
Dim strfilename As String
Dim mnth As String
Dim mnthshrt As String
mnth = Replace(strfilename, "Temporary PSD Report ", "")
mnthshrt = Replace(mnth, " 2011.xls", "")
I've tried using & and AND to reference both parts to be removed but it either has no effect on the original string or produces an error.
You could also split the string at each space character and take the 4th word (index starts at 0):
s = "Temporary PSD Report 'Month' 2011.xls"
mth = Split(s, " ")(3)

Resources