Parsing string - "Contains" is insufficient - vb.net

I use this code to check if a String is in another String:
If StringData(1).Contains("-SomeText2.") Then
'some code
End If
'StringData(1) looks like this:
'-SomeText1.1401-|-SomeText2.0802-|-SomeText3.23-|-SomeText4.104-|
'In case I look for -SomeText1. I need 1401
'In case I look for -SomeText2. I need 0802
'In case I look for -SomeText3. I need 23
'In case I look for -SomeText4. I need 104
I first check if -SomeText2. is in StringData(1), and if it is, I need to get the next part of the text: 0802 which is the part I don't know how to do, how can I do it?
All the strings are separated by | and all substrings start and end with - and have a . separating the first part from the second. I check all the strings starting with - and ending with . because there are some with - and | in the middle, so Split function won't work.
Those strings change quite often, so I need something to check it no matter the length of the strings.

I would just split the string up and get the text between "." and "-" when the search text is found like this:
Dim str As String = "-SomeText1.1401-|-SomeText2.0802-|-SomeText3.23-|-SomeText4.104-"
Dim searches() As String = {"-SomeText1", "-SomeText2", "-SomeText3", "-SomeText4"}
For Each search As String In searches
For Each value As String In str.Split(CChar("|"))
If value.Contains(search) Then
Dim partIwant As String = value.Substring(value.IndexOf(".") + 1, value.Length - value.IndexOf(".") - 2)
MsgBox(partIwant)
'Outputs: 1401, 0802, 23, 104
Exit For
End If
Next
Next
In this example, we just use Contains() to see if our search string is present or not...we can't actually use that function to get any further information because all it returns is a True or False. So once we know that our string has been found, it's just a matter of some string manipulation to grab the text between the "." and "-" characters. IndexOf() will get us the index of the period, and then we just pull the text between there and the last character of the string.

Your question has nothing to do with WPF, so the tag and title are misleading.
To solve your problem, you should use String.IndexOf(string) instead of String.Contains(string). That tells you at which position the given string starts. If that value is -1, it means that the original string does not contain your search string at all.
Once you have that starting index, you can use String.IndexOf(string, int) to search for the next occurrence of -, so you know where the entry stops. The second parameter tells it at which index it should start the search, and in this case you should start the search at the index where you found your first match.
Now that you know the starting index of your match, the end index of the entry and the length of your search string, you can put those together and easily use String.Substring(int, int) to get the part of the string that you are interested in.
That's the straight forward, naive solution. A more sophisticated solution would simply build a regular expression for the search string that is built in a way that the part you are interested in is included in the capture group. But that's a more elaborate topic.

Related

Find a time pattern within a string

My string variable may or may not contain the time, it may be anywhere within a group of words. now is 03:24 or any other possible combination of words or location with in the string. The only constant is that it will be xx:xx. I would like to detect the true or false of the xx:xx pattern within the string.
I have been playing with Regex and other solutions but I am nowhere. I'm not even sure if what I have, (collected bits and pieces) actually will work.
Use Regex.Match with the pattern \b\d{2}:\d{2}\b:
Dim regex As Regex = New Regex("\b\d{2}:\d{2}\b")
Dim match As Match = regex.Match("now is 03:24")
If match.Success Then
Console.WriteLine("MATCH")
End If
The above solution will detect the presence of a timestamp of the form 03:24 anywhere in the input string.

VB.net get specific characters from listbox

I want to get specific characters from listbox, but I don't know how to do it properly. I already used search (tried because I don't know how properly to name) but get nothing.
So i have this line in my listbox:
1,2014-01-01,Text,Text,XYZ123,Text,Text
How do i need to get only XYZ123? Its always same format, 3 letters and 3 numbers.
Thank you.
I would use a Regular Expression
The Regex of XYZ123 = \w{3}\d{3}
First solution:
Based on a small console application:
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
For Each Str As String In i.Split(",")
Dim match As Match = Regex.Match(Str, "\w{3}\d{3}")
If match.Success Then
Console.WriteLine(Str)
End If
Next
Console.ReadLine()
Second (better) solution:
Based on the comment of Chinz (all credits belong to him)
Dim i As String = "1,2014-01-01,Text,Text,**XYZ123**,Text,Text"
Console.WriteLine(Regex.Match(i, "\w{3}\d{3}").Value)
Console.ReadLine()
if all the strings have the same overall format you could split on "**" and get the [1] from the plitted

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.

A Perfectly good Substring Error

Im having a problem parsing a string array of Directories. The end goal is to query the path tied to the [global].MyDataDir & "\saved" to get all folders in this directory. However the actual foldernames, the last bit of text after the last indexof "\" holds the name of a plugin that I need to compare against an enumerated list of plugins for further functionality I won't get into here. The problem here is my last bit of code wont work. The Dim foldername as String = (etc...), It returns an error saying Index and length must refer to a location within the string. Parameter name: length.
Can any of you wizards, help me out here. Much appreciated.
Dim dirList As String() = System.IO.Directory.GetDirectories([global].MyDataDir & "\saved")
For dir As Integer = 0 To dirList.Length - 1
If IO.Directory.GetFiles(dirList(dir)).Length > 0 Then
For Each file As String In IO.Directory.GetFiles(dirList(dir))
Dim folderName As String = dirList(dir).ToString.Substring(dirList(dir).ToString.LastIndexOf("\"), dirList(dir).ToString.Length - 1)
Next
End If
Next
Semper Fi.
Use System.IO.Path.GetDirectoryName() instead.
Next time use the VB.NET Left() convenience function to avoid getting this wrong.
I found the reason....
The problem lies in the arguments of Substring(starting index, length of copy from starting index). I was under the impression, the length argument would take into account the entire string when calculating the length. Instead the second argument of this function acts upon the results of the first argument, not the entire string. So the length of the string is actually much longer than what exists after taking an index of it.
Thanks for the help.

MS-Access: Replace "bracket"

In one of the ms-access table I work with we have a text field with a set size.
At the end of this field there is some extra code that varies depending on the situation.
I'm looking for a way to remove one of these code but even when the last part is truncated by the field maximum size.
Let's call the field "field" and the code I'm looking to remove "abc-longcode".
If I use the replace SQL function with the string abc-longcode the query will only work when the code is complete.
If I also want my update query (that does nothing but remove this specific code at the end of my field) to work on incomplete codes how would that translate into ms-SQL?
It would have to remove (or replace with "" to be precise) all of the following (example of course, not the real codes):
abc-longcode
abc-longcod
abc-longco
abc-longc
abc-long
abc-lon
abc-lo
abc-l
Obviously I could do that with several queries. Each one replacing one of the expected truncated codes... but it doesn't sound optimal.
Also, when the field is big enough to get all of the code, there can sometime be extra details at the end that I'll also want to keep so I cannot either just look for "abc-l" and delete everything that follows :\
This query (or queries if I can't find a better way) will be held directly into the .mdb database.
So while I can think of several ways to do this outside of a ms-sql query, it doesn't help me.
Any help?
Thanks.
You can write a custom VBA replace method that will replace any of the given cases {"abc-longcode", ... "abc-l"}. This is essentially the same tack as your "several queries" idea, except it would only be one query. My VBA is rusty, but something like:
public function ReplaceCodes(str as string) as string
dim returnString as string
returnString = str
returnString = replace(returnString,"abc-longcode","")
// ... etc...
ReplaceCodes = returnString
end function
I may have gotten the parameter order wrong on replace :)
I would use my own custom function to do this using the split function to get the first part of the string. You can then use that value in the update query.
Public Function FirstPart(thetext As String) As String
Dim ret As String
Dim arrSplitText As Variant
arrSplitText = Split(thetext, "-")
ret = arrSplitText(0)
FirstPart = ret
End Function
Can you use:
Left(FieldX,InStr(FieldX,"abc-")-1)
EDIT re Comment
If there is a space or other standard delimiter:
IIf(InStr(InStr(FieldX, "abc-"), FieldX, " ") = 0, Left(FieldX, InStr(FieldX, "abc-") - 1), Replace(FieldX, Mid(FieldX, InStr(FieldX, "abc-"), InStr(InStr(FieldX, "abc-"), FieldX, " ") - InStr(FieldX, "abc-")), ""))