Extracting specific piece of string between brackets:
Suppose this is the string:
"[Hello][Bye]CakeBuster[Dead]"
The following function will extract 'CakeBuster' from the above string.
[highlight=vbnet]Dim Source As String = "[Hello][Bye]CakeBuster[Dead]"
Dim _1 As Integer = Source.LastIndexOf("[")
Dim Ex1 As String = Mid(Source, 1, _1)
Dim _2 As Integer = Ex1.LastIndexOf("]") + 2
Dim FinalExtraction As String = Mid(Ex1, _2)[/highlight]
A little explanation:
Dim _1 As Integer = Source.LastIndexOf("[")
This line gets the index (number) for last "[".
Dim Ex1 As String = Mid(Source, 1, _1)
This will store the string up to last "[" but not after that.
Dim _2 As Integer = Ex1.LastIndexOf("]") + 2
Similarly this will get the last index of "]" in the new string which is Ex1 now !!
Dim FinalExtraction As String = Mid(Ex1, _2)
Finally, extract the word you need by starting the string from "]".
Here is a string manipulation library from CodeProject:
Just create a new module named 'StringFunctions' and paste the following code in it:
[highlight=vbnet]Imports System.Text
Module StringFunctions
'Retrieves the path part of a full filename
'C:\Folder\file.exe -> C:\Folder\
Public Function GetPath(ByVal Full As String) As String
For i As Integer = Full.Length - 1 To 0 Step -1
If Full.Substring(i, 1) = "\" OrElse Full.Substring(i, 1) = "/" Then 'Find the rightmost \ or /, which should be cut off the file part
Return Full.Substring(0, i) & "\"
End If
Next
Return ""
End Function
'Retrieves the name of the file from a filename
'C:\Folder\file.exe - > file
'OR
'file.exe -> file
Public Function GetName(ByVal Full As String) As String
Dim Start As Integer = GetPath(Full).Length 'If it's has path it gets how long it only the path is
Return RemoveExtension(Full.Substring(Start)) 'take of the path and the extension
End Function
'Retrieves the extension of the file from a filename
'C:\Folder\file.exe - > exe
'OR
'file.exe -> exe
Public Function GetExtension(ByVal Full As String) As String
Dim Index As Integer
For i As Integer = Full.Length - 1 To 0 Step -1
Index = Full.IndexOf(".", i) 'Find the right most . (a different technique than GetPath)
If Index > -1 Then
Return Full.Substring(Index)
End If
Next
Return ""
End Function
'Removes extension from a filename
'C:\Folder\file.exe - > C:\Folder\file
'OR
'file.exe -> file
Public Function RemoveExtension(ByVal Full As String) As String
Dim Last As Integer = Full.Length - GetExtension(Full).Length
Return Full.Substring(0, Last)
End Function
'Removes path from a filename
'C:\Folder\file.exe - > file.exe
Public Function GetFullName(ByVal Full As String) As String
Return Full.Substring(GetPath(Full).Length) 'Cut off everything up to the path
End Function
'Capitalizes a word or sentence
'word -> Word
'OR
'this is a sentence -> This is a sentence
Public Function Capitalize(ByVal [String] As String) As String
If [String].Length = 1 Then Return [String].ToUpper 'one letter just return it capitalized
Return [String].Substring(0, 1).ToUpper & [String].Substring(1) 'cut the first letter and capitalize it and then add the rest
End Function
'checks whether a word or sentence is capitalized
'Word -> True
'OR
'This is a sentence -> True
Public Function IsCapitalized(ByVal [String] As String) As Boolean
Return AscW([String].Substring(0, 1)) = AscW([String].Substring(0, 1).ToUpper) 'compare the ascii value of the first letter and a capitalized first letter
End Function
'checks whether a word or char is in lower case
'word -> True
'Word -> False
Public Function IsLower(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If Not AscW([String].Substring(i, 1)) = AscW([String].Substring(i, 1).ToLower) Then Return False 'compare the asc values
Next
Return True
End Function
'checks whether a word or char is in upper case
'word -> False
'Word -> False
'WORD -> True
Public Function IsUpper(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If Not AscW([String].Substring(i, 1)) = AscW([String].Substring(i, 1).ToUpper) Then Return False 'compare asc values
Next
Return True
End Function
'swaps the cases in a word
'word -> WORD
'Word -> wORD
'WoRd -> wOrD
Public Function SwapCases(ByVal [String] As String) As String
Dim ret As New StringBuilder 'StringBuilder used to be faster on bigger strings
For i As Integer = 0 To [String].Length - 1
If IsUpper([String].Substring(i, 1)) Then 'check whether it's a capital letter or not and make it the opposite
ret.Append([String].Substring(i, 1).ToLower)
Else
ret.Append([String].Substring(i, 1).ToUpper)
End If
Next
Return ret.ToString 'Take of ".ToString" if you prefer it in StringBuilder form (and change the function to StringBuilder also)
End Function
'Alternates cases between letters of a string, first letter's case stays the same
'Hi -> Hi
'longstring -> lOnGsTrInG
Public Function AlternateCases(ByVal [String] As String) As String
If [String].Length = 1 Then Return [String] 'Can't alternate if only one letter
Dim Upper As Boolean = Not IsUpper([String].Substring(0, 1)) 'start alternation depending on the first letter's case
Dim ret As New StringBuilder([String].Substring(0, 1))
For i As Integer = 1 To [String].Length - 1
If Upper Then
ret.Append([String].Substring(i, 1).ToUpper)
Else
ret.Append([String].Substring(i, 1).ToLower)
End If
Upper = Not Upper 'switch to capitalize or not
Next
Return ret.ToString
End Function
'Checks to see if a string has alternate cases
'lOnGsTrInG -> True
Public Function IsAlternateCases(ByVal [String] As String) As Boolean
If [String].Length = 1 Then Return False 'One letter strings can't be alternate cases
Dim Upper As Boolean = Not IsUpper([String].Substring(0, 1)) 'Same structure as AlternateCases function, depends on the first letter
For i As Integer = 1 To [String].Length - 1
If Upper Then
If Not IsUpper([String].Substring(i, 1)) Then Return False
Else
If IsUpper([String].Substring(i, 1)) Then Return False
End If
Upper = Not Upper
Next
Return True
End Function
'Checks for mixed upper and lower cases
'string -> False
'String -> True
Public Function IsMixedCases(ByVal [String] As String) As Boolean
Dim upper As Boolean
For i As Integer = 0 To [String].Length - 1 'look for the first letter and see if it's capitalized or not
If IsLetters([String].Substring(i, 1)) Then
upper = IsUpper([String].Substring(i, 1))
End If
Next
If [String].Length = 1 Then Return False
For i As Integer = 1 To [String].Length - 1
If IsUpper([String].Substring(i, 1)) <> upper AndAlso _
IsLetters([String].Substring(i, 1)) Then Return True 'something has a different case, then it's now mixed, ignores numbers and others
Next
Return False
End Function
'Counts total number of a char or chars in a string
'hello, l -> 2
'hello, he -> 1
Public Function CountTotal(ByVal [String] As String, ByVal [Chars] As String) As Integer
Dim Count As Integer
For i As Integer = 0 To [String].Length - 1 Step [Chars].Length
'The way String.Compare works, "Not CBool" converts it to a traditional True/False
'Compare is used to compare ignoring capitalization
If Not i + [Chars].Length > [String].Length AndAlso Not CBool(String.Compare([String].Substring(i, [Chars].Length), [Chars], True)) Then
Count += 1
End If
Next
Return Count
End Function
'Removes vowels from a word
'remove -> rmv
Public Function RemoveVowels(ByVal [String] As String) As String
Dim ret As New StringBuilder
For i As Integer = 0 To [String].Length - 1
If Not (Not CBool(String.Compare([String].Substring(i, 1), "a", True)) OrElse Not CBool(String.Compare([String].Substring(i, 1), "e", True)) OrElse _
Not CBool(String.Compare([String].Substring(i, 1), "i", True)) OrElse Not CBool(String.Compare([String].Substring(i, 1), "o", True)) OrElse _
Not CBool((String.Compare([String].Substring(i, 1), "u", True)))) Then
'only add to the final string if it doesn't match the vowels
ret.Append([String].Substring(i, 1))
End If
Next
Return ret.ToString
End Function
'Checks to see if a word contains vowels
'hello -> True
'rmv -> False
Public Function HasVowels(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If (Not CBool(String.Compare([String].Substring(i, 1), "a", True)) OrElse Not CBool(String.Compare([String].Substring(i, 1), "e", True)) OrElse _
Not CBool(String.Compare([String].Substring(i, 1), "i", True)) OrElse Not CBool(String.Compare([String].Substring(i, 1), "o", True)) OrElse _
Not CBool(String.Compare([String].Substring(i, 1), "u", True))) Then
'if something equals one of the vowels then it has vowels
Return True
End If
Next
Return False
End Function
'Checks if string is nothing but spaces
'" " -> True
Public Function IsSpaces(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If Not AscW([String].Substring(i, 1)) = 32 Then '32 is the asc value of a space
Return False
End If
Next
Return True
End Function
'Checks if string has only numbers
'(Since parameter is String instead of Object, it should be faster)
'12453 -> True
'234d3 -> False
Public Function IsNumeric(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If Not (AscW([String].Substring(i, 1)) >= 48 AndAlso AscW([String].Substring(i, 1)) <= 57) Then 'asc value range of numbers
Return False
End If
Next
Return True
End Function
'Checks if the string contains numbers
'hello -> False
'h3llo -> True
Public Function HasNumbers(ByVal [String] As String) As Boolean
Return System.Text.RegularExpressions.Regex.IsMatch([String], "\d+")
End Function
'Checks if string is numbers and letters
'Test1254 -> True
'$chool -> False
Public Function IsAlphaNumberic(ByVal [String] As String) As Boolean
For i As Integer = 0 To [String].Length - 1
If Not (IsNumeric([String].Substring(i, 1)) OrElse _
(AscW([String].Substring(i, 1)) >= 65 AndAlso AscW([String].Substring(i, 1)) <= 90) OrElse _
(AscW([String].Substring(i, 1)) >= 97 AndAlso AscW([String].Substring(i, 1)) <= 122)) Then
'checks asc value range of lower case and upper case letters and check if it's a number, if either fail, then it's not
'only numbers and letters
Return False
End If
Next
Return True
End Function
'Checks if a string contains only letters
'Hi -> True
'Hi123 -> False
Public Function IsLetters(ByVal [String] As String) As Boolean
If IsAlphaNumberic([String]) Then 'Only numbers and letters, good
If Not IsNumeric([String]) Then 'no numbers, good
Return True
End If
End If
Return False
End Function
'Returns the initials of a name or sentence
'Capitalize - whether to make intials capitals
'ReturnSeparator - to return intials separated (True - J. S. or False - J.S.)
'John Smith -> J. S. or J.S.
Public Function Initials(ByVal [String] As String, ByVal Capitalize As Boolean, ByVal ReturnSeparator As Boolean, Optional ByVal Separator As String = " ") As String
Dim strs As String() = [String].Split(Separator) 'split all the words
For i As Integer = 0 To strs.Length - 1
'Leave only the first letter of everyword and add a . after each
If Capitalize Then
strs(i) = strs(i).Substring(0, 1).ToUpper & "."
Else
strs(i) = strs(i).Substring(0, 1) & "."
End If
Next
If ReturnSeparator Then
Return String.Join(Separator, strs)
Else
Return String.Join("", strs) 'No separator
End If
End Function
'Capitalizes the first letter of every word
'the big story -> The Big Story
Public Function Title(ByVal [String] As String, Optional ByVal Separator As String = " ") As String
Dim ret As String
If [String].IndexOf(Separator) > -1 Then
Dim strs As String() = [String].Split(Separator) 'split all the words so to capitalize the first letter of each
For i As Integer = 0 To strs.Length - 1
If strs(i).Length = 1 Then
strs(i) = strs(i).ToUpper
Else
strs(i) = strs(i).Substring(0, 1).ToUpper & strs(i).Substring(1)
End If
Next
ret = String.Join(Separator, strs) 'join them back together
End If
Return ret
End Function
'Checks whether the first letter of each word is capitalized
'The Big Story -> True
'The big story -> False
Public Function IsTitle(ByVal [String] As String, Optional ByVal Separator As String = " ") As Boolean
If [String].IndexOf(Separator) > -1 Then
Dim strs As String() = [String].Split(Separator) 'split the words to check the first letter of each word is capitalized
For i As Integer = 0 To strs.Length - 1
If Not AscW(strs(i).Substring(0, 1)) = AscW(strs(i).Substring(0, 1).ToUpper) Then Return False
Next
End If
Return True
End Function
'Checks if string is a valid emailaddress-format
'name@place.com -> True
'hahaimfaking -> False
'(Function works assuming the last part is no bigger than 3 letters (com, net, org))
Public Function IsEmailAddress(ByVal [String] As String) As Boolean
If [String].IndexOf("@") > -1 Then
For i As Integer = [String].Length - 1 To 0 Step -1
If [String].Substring(i, 1) = "." Then
If [String].Length - i <= 4 Then
Return True
End If
End If
Next
End If
Return False
End Function
'Returns all the locations of a char in a string
'Hello, l -> 2, 3
'Hello, o -> 4
Public Function IndexesOf(ByVal [String] As String, ByVal [Char] As String) As Integer()
Dim inx As New ArrayList
For i As Integer = 0 To [String].Length - 1
If [String].Substring(i, 1) = [Char] Then inx.Add(i) 'for every location found add it
Next
Dim final(in*****unt - 1) As Integer
in*****pyTo(final) 'convert the ArrayList to an Integer array
inx.Clear()
Return final
End Function
'Return a rating for how strong the string is as a password
'Max rating is 100
'Credits for original function to D. Rijmenants, this is just a vb.net version
'If there are problems with copyright or whatever, contact me and i'll delete this
Public Function PasswordStrength(ByVal [String] As String) As Integer
Dim Total As Integer
Dim Uc As Boolean
Dim Lc As Boolean
Total = [String].Length * 3
For i As Integer = 1 To [String].Length - 1
If AscW([String].Substring(i, 1)) >= 65 AndAlso AscW([String].Substring(i, 1)) <= 92 Then Uc = True 'contains uppercases
Next
For i As Integer = 1 To [String].Length - 1
If AscW([String].Substring(i, 1)) >= 97 And AscW([String].Substring(i, 1)) <= 122 Then Lc = True 'contains lowercases
Next
If Uc = True And Lc = True Then Total *= 1.2
For i As Integer = 1 To [String].Length - 1
If AscW([String].Substring(i, 1)) >= 48 And AscW([String].Substring(i, 1)) <= 57 Then 'contains numbers
If Uc = True Or Lc = True Then Total *= 1.4
Exit For
End If
Next
For i As Integer = 1 To [String].Length - 1
If AscW([String].Substring(i, 1)) <= 47 Or AscW([String].Substring(i, 1)) >= 123 Or (AscW([String].Substring(i, 1)) >= 58 And AscW([String].Substring(i, 1)) <= 64) Then
'contains some extra symbols
Total *= 1.5
Exit For
End If
Next
If Total > 100 Then Total = 100 'make sure not over 100
Return Total
End Function
'Gets the char in a string at a given position, but from right to left
'string, 0 -> g
Public Function CharRight(ByVal [String] As String, ByVal Position As Integer) As Char
Return [String].Substring([String].Length - Position - 1, 1)
End Function
'Gets the char in a string at a given position from the given starting point, reads left to right
'string, 0, 2 -> r
Public Function CharMid(ByVal [String] As String, ByVal Position As Integer, ByVal Start As Integer) As Char
If Not Start + Position > [String].Length Then
Return [String].Substring(Start + Position, 1)
Else
Return ""
End If
End Function
'Inserts a separator after every letter
'hello, - -> h-e-l-l-o
Public Function InsertSeparator(ByVal [String] As String, ByVal Separator As String) As String
Dim final As New StringBuilder
For i As Integer = 0 To [String].Length - 1
final.Append([String].Substring(i, 1) & Separator) 'after every letter add the separator
Next
Return final.ToString.Substring(0, final.Length - 1) 'Cut out last separator (h-e-l-l-o- -> h-e-l-l-o)
End Function
'Inserts a separator after every Count letters
'hello, -, 2 -> he-ll-o
Public Function InsertSeparatorEvery(ByVal [String] As String, ByVal Separator As String, ByVal Count As Integer) As String
Dim final As New StringBuilder
For i As Integer = 0 To [String].Length - 1 Step Count 'every so steps add the separator
If Not i + Count > [String].Length Then
final.Append([String].Substring(i, Count) & Separator)
Else
final.Append([String].Substring(i) & Separator)
End If
Next
Return final.ToString.Substring(0, final.Length - 1) 'Cut out last separator
End Function
'Inserts a separator at given position
'hello, -, 3 -> hel-lo
Public Function InsertSeparatorAt(ByVal [String] As String, ByVal Separator As String, ByVal Position As Integer) As String
Return [String].Substring(0, Position) & Separator & [String].Substring(Position) 'split the string at that position and add the separator
End Function
'Function that works the same way as the default Substring, but
'it takes Start and End parameters instead of Start and Length
Public Function Substring(ByVal [String] As String, ByVal Start As Integer, ByVal [End] As Integer) As String
If Start > [End] Then 'If start is after the end then just flip the values
Start = Start Xor [End]
[End] = Start Xor [End]
Start = Start Xor [End]
End If
If [End] > [String].Length Then [End] = [String].Length 'if the end is outside of the string, just make it the end of the string
Return [String].Substring(Start, [End] - Start)
End Function
'Reverses a string
'Hello -> olleH
Public Function Reverse(ByVal [String] As String) As String
Dim final As New StringBuilder
For i As Integer = [String].Length - 1 To 0 Step -1 'read the string backwards
final.Append([String].Substring(i, 1))
Next
Return final.ToString
End Function
'Splits strings, but leaves anything within quotes
'This is a "very long" string ->
'This
'is
'a
'very long
'string
Public Function Split(ByVal [String] As String, Optional ByVal DontAccountQuotes As Boolean = False, Optional ByVal Separator As String = " ") As String()
If DontAccountQuotes Then
Return [String].Split(Separator)
Else
Dim words As String() = [String].Split(Separator)
Dim newwords As New ArrayList
For i As Integer = 0 To words.Length - 1
If words(i).StartsWith("""") Then
Dim linked As New ArrayList
For y As Integer = i To words.Length - 1
If words(y).EndsWith("""") Then
linked.Add(words(y).Substring(0, words(y).Length - 1))
i = y
Exit For
Else
If words(y).StartsWith("""") Then words(y) = words(y).Substring(1)
linked.Add(words(y))
End If
Next
Dim tmp(linked.Count - 1) As String
linked.CopyTo(tmp)
If Not linked.Count = 0 Then newwords.Add(String.Join(Separator, tmp))
linked.Clear()
Erase tmp
Else
newwords.Add(words(i))
End If
Next
Dim tmp2(newwords.Count - 1) As String
newwords.CopyTo(tmp2)
newwords.Clear()
Return tmp2
End If
End Function
End Module
[/highlight]
Functions are:
GetPath(<Full Path>)
The function retrieves the path part from the full filename like, C:\Folder\file.exe -> C:\Folder\.
GetName(<Full Path>)
It retrieves the name of the file from the full filename like, C:\Folder\file.exe - > file, file.exe -> file.
GetExtension(<Full Path>)
It retrieves the extension of the file from a filename C:\Folder\file.exe - > exe, file.exe -> exe.
RemoveExtension(<Full Path>)
It removes the extension from a filename like, C:\Folder\file.exe - > C:\Folder\file, file.exe -> file.
GetFullName(<Full Path>)
It removes the path from a filename like, C:\Folder\file.exe - > file.exe.
IsCapitalized(<String>)
It checks whether a word or sentence is capitalized like, Word -> True, This is a sentence -> True.
IsLower(<String>)
It checks whether a word or character is in lower case like, word -> True, Word -> False.
IsUpper(<String>)
It checks whether a word or character is in upper case like, word -> False, Word -> False, WORD -> True.
SwapCases(<String>)
It swaps the cases in a string like, word -> WORD, Word -> wORD, WoRd -> wOrD.
AlternateCases(<String>)
It alternates the cases between letters of a string, the first letter's case stays the same like, Hi -> Hi, longstring -> lOnGsTrInG.
IsAlternateCases(<String>)
It checks to see if a string has alternate cases like, lOnGsTrInG -> True.
IsMixedCases(<String>)
It checks for mixed upper and lower cases like, string -> False, String -> True.
CountTotal(<String>, <Chars>)
It counts total number of a string or character in a string like, hello, l -> 2, hello, he -> 1.
RemoveVowels(<String>)
It removes vowels from a string like, remove -> rmv.
HasVowels(<String>)
It checks to see if a string contains vowels like, hello -> True, rmv -> False.
IsSpaces(<String>)
It checks if a string is nothing but spaces like, " " -> True.
IsNumeric(<String>)
It checks if a string has only numbers like, 12453 -> True, 234d3 -> False.
I know that there is already an existing IsNumeric function, but the existing one takes the input parameter as an Object, so in theory, this function should be faster for larger strings because it takes the input as a String.
HasNumbers(<String>)
It checks if the string contains numbers like, hello -> False, h3llo -> True.
IsAlphaNumberic(<String>)
It checks if the string has numbers and letters like, Test1254 -> True, $chool -> False.
IsLetters(<String>)
It checks if the string contains only letters like, Hi -> True, Hi123 -> False.
Initials(<String>, <Capitalize>, <ReturnSeparator>, <Optional Separator = " ">)
It returns the initials of a name or sentence.
* Capitalize- To return the initials as lower or upper case.
* ReturnSeparator - To return the initials with the original separator (John Smith, a space is the separator, so return J. S. or J.S.).
* Separator - The character that marks the separation of words (John Smith, space is the separator (default)) John Smith -> J. S.
Title(<String>, <Optional Separator = " ">)
It capitalizes the first letter of every word in the string like, the big story -> The Big Story.
IsEmailAddress(<String>)
It checks if a string is in a valid email address-format like,
name@place.com -> True, hahaimfaking -> False. (The function works by assuming the last part is no bigger than 3 letters (com, net, org).)
IndexesOf(<String>, ByVal [Char] As String) As Integer()
It returns all the locations of a given char in a string like, Hello, l -> 2, 3, Hello, o -> 4.
This function works with an ArrayList and then converts it to an Integer array, if you prefer the ArrayList it can be easily modified.
CharRight(<String>, <Position>) As Char
It gets the char in a string at a given position, but from right to left like, string, 0 -> g.
CharMid(<String>, <Position>, <Start>) As Char
It gets the char in a string at a given position from a given starting point, and reads from left to right like, string, 0, 2 -> r.
InsertSeparator(<String>, <Separator As String>)
It inserts a separator after every letter like, hello, "-" -> h-e-l-l-o.
InsertSeparatorEvery(<String>, <Separator>, <Count>)
It inserts a separator after every Count letters like, hello, "-", 2 -> he-ll-o.
Substring(<String>, <Start>, <End>)
This is a function that works the same way as the default Substring, but it takes Start and End parameters instead of Start and Length.
Reverse(<String>)
It reverses a string like, Hello -> olleH.
PasswordStrength(<String>) As Integer
It is a borrowed function. It returns a rating for how strong the string is as a password. (Max rating is 100).
The credits for the original function goes to D. Rijmenants, this is just a VB.NET version. If there is any problem with copyright or whatever, contact me and I'll delete this. This is just an interesting function that took me a long time to find, so I thought it'd be useful to include it here.
Split(<String>, <Optional Don't Account for Quotes>, <Optional Separator>)
This function is newly added (on 9/27/05). Thanks to j1webb for the idea. This is just like the default Split function, but it keeps everything inside the quotes, intact. For example: 'This is a "very long" string' would return 'This', 'is', 'a', 'very long', 'string'. A limitation of this function is that if there's a quote inside quotes it will mess up. The quote symbol is " by default, but it can be changed to look for ' instead.
Hope this helps !!!