VB.NET string.replace() isn't always working as expected - vb.net

Data examples:
EFT- MONTREAL || 378 STREET AVE
EFT TORONTO1 || TESTING 875 RD ADDRESS
What I need extract from these:
EFT- MONTREAL
EFT TORONTO1 (note: end of this line is extra space)
Is this the correct way to extract?
String.Split(" || ")(0)
The problem is, sometimes I get these values saved to Database:
EFT-
EFT
I just want to know which way is the correct one so I can change every line to the correct one.

No, there is no overload that accepts a string. So you are actually using the overload of String.Split which accepts a ParamArray Char(). But this will check if any of these chars match, so not only if the whole sub-string matches. It is the same as this:
Dim first = text.Split(" "c, "|"c, "|"c, " "c)(0) ' "EFT-"
Use this instead:
Dim first = text.Split({" || "}, StringSplitOptions.RemoveEmptyEntries)(0)
Note that you can also use StringSplitOptions.None, that's not the problem.
String.Split Method(String(), StringSplitOptions)
Returns a string array that contains the substrings in this string
that are delimited by elements of a specified string array. A
parameter specifies whether to return empty array elements.
But note that you should set OPTION STRICT to on, then your code would not even compile since a string is not a Char() implicitly. With OPTION STRICT off it will be converted silently.
Option Strict on by default in VB.NET

Related

How to add an item to a combobox (using AddItem()) which contains a semicolon?

I have a multi-column combobox on an Access form (Access 2019 x64, if that matters) and would like to use its AddItem() method to populate it as described in this documentation. Citing from it:
For multiple-column lists, use semicolons to delimit the strings for
each column (for example, "1010;red;large" for a three-column list).
If the Item argument contains fewer strings than columns in the
control, items will be added starting with the left-most column. If
the Item argument contains more strings than columns in the control,
the extra strings are ignored.
So it is impossible to add a string for a certain column when the string itself already contains a semicolon?
Surround the column value which contains the semi-colon with double-quotes, e.g.:
AddItem """Column1;A"";Column2;Column3"
Will yield:
+-----------+---------+---------+
| Column1;A | Column2 | Column3 |
+-----------+---------+---------+
All credits go to #Lee Mac who answered my original question completely. However, the answer immediately raised the question how we should treat strings which already have quotes in them.
Therefore, I have written the following function in VBA which seems to solve the problem completely. The comments should be self-explaining. Please comment if you find an error.
I have posted this as separate answer because it's way too long for a comment, and because it seems that the community does not prefer such answers edited into the original question.
'Notes:
'
'The following function quotes an arbitrary string so that it can be
'used as part of the parameter to the ComboBox.AddItem() method.
'Writing that function was necessary because there is no easy way to
'use strings which already contain the ; character as part of that
'parameter, or which even contain the ; character as well as double
'quotes; see also Microsoft's documentation.
'
'To construct the parameter for the AddItem() method, the following
'must be done:
'
'For EACH column, the source string must be quoted using the following
'function. Then, all QUOTED strings must be concatenated, separating
'them only by one ; character.
'
'Successfully tested 2019-10-03 in Access 2019 / 64-bit / VBA with a
'standard combobox on a form.
Public Function QuoteStringForValueList(sString As String) As String
Dim sTemp As String, sDDQ As String
'String containing two double quotes to make reading easier
sDDQ = Chr(34) & Chr(34)
'Replace each double quote by four double quotes
sTemp = Replace(sString, Chr(34), sDDQ & sDDQ)
'Add two leading and two trailing double quotes
QuoteStringForValueList = sDDQ & sTemp & sDDQ
End Function

Isolate a a substring within quotes from an entire line

To start here is an example of a line I am trying to manipulate:
trait slot QName(PrivateNamespace("*", "com.company.assembleegameclient.ui:StatusBar"), "_-0IA") type QName(PackageNamespace(""), "Boolean") value False() end
I wrote a code that will go through and read through each line and stop at the appropriate line. What I am trying to achieve now is to read through the characters and save just the
_-0IA
to a new string. I tried using Trim(), Replace(), and indexof so far but I am having a ton of difficulties because of the quotation marks. Has anyone deal with this issue before?
Assuming your source string will always follow a strict format with only some data changes, something like this might work:
'Split the string by "," and extract the 3rd element. Trim the space and _
quotation mark from the front and extract the first 5 characters.
Dim targetstr As String = sourcestr.Split(","c)(2).TrimStart(" """.ToCharArray).Substring(0, 5)
If the length of the target string is variable it can be done like this:
Dim temp As String = teststr.Split(","c)(2).TrimStart(" """.ToCharArray)
'Use the index of the next quotation mark instead of a fixed length
Dim targetstr As String = temp.Substring(0, temp.IndexOf(""""c))

Value of type '1-dimensional array of String' cannot be converted to 'String'. (BC30311)

I have this code which gives an error:
'declaration
Dim strFieldValues As String
'split
strFieldValues = strRecord.Split(",") 'field are separated by commas
Well, the error seems to be pretty self-explanatory to me. You've declared a variable of type String - i.e. it can hold a value of a single String reference:
Dim strFieldValues As String
You've then tried to assign a value to it returned from String.Split():
strFieldValues = strRecord.Split(",")
Now String.Split() returns a String array, not a single string value.
So you have two courses of action open to you:
Change strFieldValues to an array variable
Change the value you assign to it
My guess is that you want the first, but we don't know what you're trying to achieve. The simplest approach would be to combine declaration and initialization:
Dim strFieldValues = strRecord.Split(",")
You may also need to change the arguments to Split - I don't know how VB will sort out that call.
If all you want to do is just retrieve either side of the resulting string array, you could just invoke the left or right part like this:
strFieldValues = strRecord.Split(",")(0) ' Text to the left of the delimiter character
Or
strFieldValues = strRecord.Split(",")(1) ' Text to the right of the delimiter character
Of course, this assumes that the delimiter character does exist, so you should take the necessary precautions to ensure that you won't run into a runtime exception if said character is not found on the string you are splitting.

Extracting characters from an input string vb.net

Hey guys I'm stuck with this question. Please help.
I want to write a program that can extract alphabetical characters and special characters from an input string. An alphabetical character is any character from "a" to "z"(capital letters and numbers not included") a special character is any other character that is not alphanumerical.
Example:
string = hello//this-is-my-string#capetown
alphanumerical characters = hellothisismystringcapetown
special characters = //---#
Now my question is this:
How do I loop through all the characters?
(the for loop I'm using reads like this for x = 0 to strname.length)...is this correct?
How do I extract characters to a string?
How do I determine special characters?
any input is greatly appreciated.
Thank you very much for your time.
You could loop through each character as follows:
For Each _char As Char In strname
'Code here
Next
or
For x as integer = 0 to strname.length - 1
'Code here
Next
or you can use Regex to replace the values you do not need in your string (I think this may be faster but I am no expert) Take a look at: http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
Edit
The replacement code will look something as follows although I am not so sure what the regular expression (variable called pattern currently only replacing digits) would be:
Dim pattern As String = "(\d+)?" 'You need to update the regular expression here
Dim input As String = "123//hello//this-is-my-string#capetown"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, "")
Since you need to keep the values, you'll want to loop through your string. Keeping a list of characters as a result will come in handy since you can build a fresh string later. Then take advantage of a simple Regex test to determine where to place things. The psuedo code looks something like this.
Dim alphaChars As New List(Of String)
Dim specialChars As New List(Of String)
For Each _char As Char in testString
If Regex.IsMatch(_char, "[a-z]")) Then
alphaChars.Add(_char)
Else
specialChars.Add(_char)
End If
Next
Then If you need to dump your results into a full string, you can simply use
String.Join(String.Empty, alphaChars.ToArray())
Note that this code makes the assumption that ANYTHING else than a-z is considered a special character, so if needs be you can do a second regular expression in your else clause to test for you special characters in a similar manner. It really depends on how much control you have over the input.

VB.NET split string with quotation marks in it

Trying to split a line wherever "," appears (with the quotation marks). The problem is VB.NET uses " to start/end strings, so I tried using .Split(""",""") but that then splits it by " not ",".
Try something like this:
Dim TestToSplit As String = "Foo"",""Bar"
Dim Splitted() As String = TestToSplit.Split(New String() {""","""}, StringSplitOptions.None)
I just tested it and got an array with Foo And Bar. I hope this helps.
The Split function (the way you are using it) expects a Char. If you want to split on multiple characters you need to use a string array. (Seems to me another overload of a single string value would have been handy.)
This function splits a line of text and returns an array based on the delimiter you have specified. (Of course, you could make this more general purpose by passing in the separator array.)
Private Function SplitLine(ByVal lineOfText As String) As String()
Dim separator() As String = {""","""}
Dim result() As String
result = lineOfText.Split(separator, StringSplitOptions.None)
Return result
End Function
Another alternative I often find useful is this:
Regex.Split(textToSplit, """,""")
Lets you split on more complex criteria than an array of alternative separators.
To escape the "-character in VB.NET, use two: ""