Find a time pattern within a string - vb.net

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.

Related

name.split based on multiple delimiters that have some of the same characters

I have files coming into SFTP that are in the following format: 12345678_STLREPT. On occasion, they have two underscores instead of one. ie: 12345678__STLREPT. This throws my sorting program through a loop. So I attempted to do the top line of code below first, it threw an I/O exception. The second line I can make work if I add "__" as a delimiter, but my question is how does Name.Split work. I haven't been able to determine through my google searches if it stops at the first delimiter it finds in the string.
Basically, If it goes through the list of delimiters it would ideally match one of them, perform the split, then stop before performing the rest.
Example:
Say I have a file, named 1234__ASDF.PDF
Would the following code split it once for the first delimiter (__) then two more times for the second (_)? I feel like it would.
fileInfo.Name.Split(New Char() {"__", "_", "-"})
Is anyone aware of a better solution to this problem?
Thank you,
Code, again. Top throws error, bottom is existing code:
fileInfo = fileInfo.Name.Replace("__", "_")
Dim a() As String = fileInfo.Name.Split(New Char() {"_", "-"})
First, be aware of your data types and what you are stuffing into them. A Char holds a single character. Trying to stuff two hyphens into a Char - for shame.
Next, be aware of your tools. The Split function accepts a second parameter that controls how empty elements should be handled. It also includes overloads for accepting a string array.
Dim fileParts As String() = fileInfo.Name.Split(
New Char() {"_", "-"},
StringSplitOptions.RemoveEmptyEntries)

Search directory where search term contains only part of the file name

How to find all files in directory when only part of the file name is known.
I've play lists downloaded from the internet. Some file name are complete and easy to find using
getfiles(searchString)
but others have words missing from the beginning or the middle of the file name. Complicating matters even more, many of the file names contain the same words differing in placement of a word within the title and others have the addition of an extra word which is included in the result when wild card character is used in place of the missing words.
What a mouthful.
I need to be able to enter the known file name words into a variable, like one enters the search term into the File Explorer file search utility, and have the best matches returned.
I've tried using
location.Getfile("*term0*term1*term3*.mp3")
This results in a hit and miss result. It can include names that should not be included. This usually results in files that should have been moved but have not. I can take the same search term (- the *) and put it into the File Explorer search and it returns only the correct file, highlighting the matched words and the unmatched words un-highlighted.
I've tried Regex as follows:
Files are:
A Day with Phil Harris.mp3
A Dog for the Kids.mp3
A Fight in the Market.mp3
A Job with Rexall for Willie.mp3
For Each Itm in location.GetFiles()
FoundMatch = Regex.IsMatch(itm.Name, "\b(?:Day|with|A)\b",
RegexOptions.IgnoreCase)
Next
This returns all 4 files because each file contains at least 1 word. If the result was best match which included the entire search term and left out the lesser matches, I could trap the result in the for each.
I've also considered looping and recursive seach of results trying to refine the final result to only the file name with the most matched words. I'm sure this would work but it seems to be more work than it should be. (For computer not me, once code is written)
I've searched the web, phrasing and rephrasing my search terms. I've learned a lot over the last 24 hours but not what I'm really am after.
Any ideas, suggestions, pointers, etc. to get me going in the correct direction? They would be gratefully appreciated.
The time consuming part is accessing the files on the disk. Counting the words is peanuts for the computer. You can increase speed by reusing the same compiled regex:
'Before the loop!
Regex regex = New Regex("\b(?:Day|with|A)\b",
RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Then inside the loop
Dim matches = regex.Matches(itm.Name)
You could use a list containing the filenames with the most matches
Dim found As New List(Of String)
Dim bestMatchCount As Integer = 0
Dim regex = New Regex("\b(?:Day|with|A)\b",
RegexOptions.Compiled Or RegexOptions.IgnoreCase)
For Each Itm In location.GetFiles()
Dim matches = regex.Matches(Itm.Name)
If matches.Count > bestMatchCount Then
found.Clear() ' Remove any previously added not so good matches
bestMatchCount = matches.Count
End If
found.Add(Itm.Name)
Next

Parsing string - "Contains" is insufficient

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.

How to remove part of a string backwards?

I have a vb string with this value: c:\program\bin\files
I need to convert this string to this value: files
All i need is the last folder of the path.
The path is not fixed. It can be anything like: d:\app\win\7\sp1\update
In this case the string must be converted to: update
I think that should be done by searching the string backwards for the first occurrence of \ and removing everything before it, including the \ itself.
But obviously i don't know how to do it. :)
Thank you!
EDIT:
I need to use this to fill a ComboBox...
This is what i am using:
ComboBox1.Items.AddRange(IO.Directory.GetDirectories(appPath & "\Updates\Version"))
It gives me a ComboBox like:
c:/program/Updates/Version/Beta1
c:/program/Updates/Version/Beta2
c:/program/Updates/Version/Beta3
c:/program/Updates/Version/Beta4
And i would like to have the ComboBox like:
Beta1
Beta2
Beta3
Beta4
Rather than try to pull apart the string yourself, have a look at the System.IO.Path class.
In your case, the GetFileName method does what you want:
lastFolder = System.IO.Path.GetFileName(path)
To fill a combo box with names you can use a LINQ query like this:
ComboBox1.Items.AddRange(
From path
In IO.Directory.GetDirectories(IO.Path.Combine(appPath, "Updates\Version"))
Select IO.Path.GetFileName(path))
Also, try to use the Path.Combine method when joining path fragments together. It's safer than just joining strings.
In VBScript, which this is tagged you have two choices. This was written before any code was edited into the question.
Use InstrR which is Instr but from back to front of string.
You also have StrReverse which reverses a string.
InStrRev
Returns the position of an occurrence of one string within another, from the end of string.
InStrRev(string1, string2[, start[, compare]])
StrReverse
Returns a string in which the character order of a specified string is reversed.
StrReverse(string1)
If using the File System Object it has a method to do specifically what you want.
GetParentFolderName Method
Returns a string containing the name of the parent folder of the last component in a specified path.
Set fso = CreateObject("Scripting.FileSystemObject")
object.GetParentFolderName(path)

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.