I'm trying to split a string in VB.NET at everything except normal letters.
I tried to write a function using Char.IsLetter(...) but it didn't work too well for some reason (I put a comment where it crashed):
Private Function splitAtNonLetter(ByVal SplitString As String) As String()
Dim NonCharSplitArray As String() = {}
Dim ProcessValueTemp As String = String.Empty
For Each Letter As Char In SplitString
If Char.IsLetter(Letter) Then
ProcessValueTemp += Letter.ToString
Else
NonCharSplitArray(NonCharSplitArray.Length) = ProcessValueTemp
ProcessValueTemp = String.Empty
End If
Next
If ProcessValueTemp.Length > 0 Then
' Crashes in the next line: Index out of range exception...
NonCharSplitArray(NonCharSplitArray.Length) = ProcessValueTemp
End If
Return NonCharSplitArray
End Function
(I tried to use Regular Expressions but I've never used them before so I didn't really manage to get it to work either)
Is there a way to do it with RegExps or do you have to write a new function and how would it work?
Regex.Split is probably the way to go, using a negative character group.
For example:
Dim bits = Regex.Split(text, "[^a-zA-z]")
Or to cope with non-ASCII letters as well:
Dim bits = Regex.Split(text, "[^\p{L}]")
Related
I could not find this question on stack overflow but if it is here, please let me know and I will take it down.
Using LINQ in VB.NET, how do you return True if a string contains one of the items in an array of strings?
This is this is the code in multiple lines. How do you do this in one line with LINQ in VB.NET?
Sub Main
Dim endPointTimeoutText As Array = {"endpoint timeout", "endpoint is not available"}
Dim strResult As String = "endpoint is not available sample text."
Dim booleanResult As Boolean = False
For Each item As String In endPointTimeoutText
If strResult.Contains(item) Then
booleanResult = True
Exit For
End If
Next
Console.WriteLine(booleanResult) 'Only included this for the example
End Sub
The expected result would be 'True' or 'False' depending on if the string (strResult) contained one of the values in the Array Of Strings (endPointTimeoutText)
You turn it around, mentally - don't ask "for this string X, which of these things in this array are in that string", you ask "for this array of strings, which of them are in this one string X":
Dim whichStringsArePresent = endPointTimeoutText.Where(Function(ett) strResult.Contains(ett))
Dim firstImeoutStringFound = endPointTimeoutText.FirstOrDefault(Function(ett) strResult.Contains(ett))
Dim wasATimeout = endPointTimeoutText.Any(Function(ett) strResult.Contains(ett))
etc
By the way it would make your code read more nicely if you make it so that Collections of things have plural names. Consider something more like this:
Dim wasATimeout = endPointTimeoutTexts.Any(Function(ett) strResult.Contains(ett))
It's subtle, but significant in terms of readability
Thank you Caius Jard for your help on this. I am going to post the complete program for what I'm going to use as the answer below.
I needed to use a List instead of an Array so that I could use the 'Any()' method. Thanks again Caius, I really appreciate it!
Sub Main
Dim endPointTimeoutText As String = "endpoint timeout,endpoint is not available"
Dim endPointTimeoutList As New List(Of String)
Dim strResult As String = "endpoint is not available sample text."
endPointTimeoutList = endPointTimeoutText.Split(",").ToList()
Dim areAnyStringsPresent As Boolean
areAnyStringsPresent = endPointTimeoutList.Any(Function(itemInEndPointTimeoutList) strResult.Contains(itemInEndPointTimeoutList))
Console.WriteLine(areAnyStringsPresent)
'This code produces the following output:
'True
End Sub
I'm struggling to solve a small bit of code. What the code does is to first load a CSV file, line by line (starting by line 3), and add it to an array. Then run a regex match and I want to insert the value in an array.
This is my working code, it shows a msgbox with the actual matches:
Dim file = "C:\Users\David\Desktop\mycsv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
MsgBox(langmatch.Value & linefilename.Value)
Next
That works well and the actual matches is what I want. So my next step was to add each match to an array to then use it to generate other files.
Therefore I ended up with this:
Dim file = "C:\Users\David\Desktop\myscv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
' Set all value line by line
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
MsgBox(langmatch.Value & linefilename.Value)
Next
After adding the below the program crashes on that line
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
I am assuming you can add the value of a regex match to a certain position of a string, but it seems I am wrong.
I´ve been searching for an answer with no results (at least to my poor understanding).
How could I convert each of the matches to a string and add it to the i position of the array?
Thanks in advance!
UPDATE:
As #Tval explained, I solved it by including the size of the array when declaring it. Thanks!
Dim filename(UBound(statistics)) As String
Dim lang(UBound(statistics)) As String
you need to initialize the array before you can reference it or you'll get a null reference error, also you can't reference an index that doesn't exist yet or you'll get an index out of range exception.
right now your using an array with a fixed length, so if you want to add a value to it you'll have to re-declare it one index larger every time.
If you want an array of a variable length id suggest using a list, so you can just append values to it without any issues
Dim myList = New List(Of String)
For Each foo As String In bar
myList.Add(bar)
Next
Here's my code so far:
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To stringArray.Length()
' Logic goes here
Next
VB6 doesn't seem to like me using stringAray.Length() and gives me a compile error message like Invalid Qualifier, but what's the right way to iterate through each element of a string array?
ubound() returns the upper bounds;
Dim i As Long
Dim stringArray(1) as String
stringArray(0) = "hello"
stringArray(1) = "world"
For i = 0 To ubound(stringArray)
msgbox(stringArray(i))
Next
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To ubound(stringArray)
' Logic goes here
Next
This is the coding for above questions.
I have re do and also include the output using Visual Basic 6.0
it is pretty simple and easy to understand.
However,I wanted to try for more iteration.
click here for the coding and the output
I have a string. For example stringone/string2
How do I get the section before the "/" and also after the "/"
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
Dim stringBefore As String = wordArr(???)
Dim stringBefore As String = wordArr(???)
What is the next step
Split() returns an Array. The first element is at Index 0 (zero), the second element is at Index 1 (one), etc...
You should check to make sure the returned array is your expected size (at least), otherwise you'll get an error attempting to access an index slot that doesn't exist.
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
If wordArr.Length = 2 Then
Dim stringBefore As String = wordArr(0)
Dim stringAfter As String = wordArr(1)
Debug.Print("stringBefore = " & stringBefore)
Debug.Print("stringAfter = " & stringAfter)
End If
*By the way, the code you posted is not VB6, it's VB.Net.
What I want to do is to count the number of words a variable has. It's for a hangman game, and will be separated by commas. So I'm basically hoping that the variable will look something like this:
"hang,man,group,toll,snail"
I'm planning on splitting it with the commas to create an array, but apart from that, I'm totally lost on what to do.
On the other hand, I'm more than happy to see any other suggestions for sorting out words to be used in a hangman game!
You're halfway there.
Dim wordCount as Integer = "hang,man,group,toll,snail".Split(",").Length
This splits it into an array, and then returns the number of elements in that array.
Dim Words as String = "hang,man,group,toll,snail"
Dim Word = Words.Split(",")
So the result will be .. Word(0) = "hang", Word(1) = "man" ... so on ..
use Split like so
Dim words As String() = SOMESTRING.Split(New Char() {","c})
now to find length you can
words.length ' set this to a variable or output
alternativly you can also use the words individually
words(0) ' set this to a variable or output
words(1) ' set this to a variable or output
and so on
You can easily split a string into an array by using the String.Split method.
There are a number of overloads, however the one I use most often is this one:
Dim myString as String = "hang,man,group,toll,snail"
Dim myStringArray as String()
myStringArray = myString.Split(new String { "," }, StringSplitOptions.None)
This will give you a string array of length 5.
Documentation can be found here: http://msdn.microsoft.com/en-us/library/tabh47cf.aspx
Dim Text As String
Dim i As Integer
Dim ary() As String
Text = "hang,man,group,toll,snail"
ary = Text.Split(",")
For i = 0 To UBound(ary)
MsgBox(ary(i)) 'here you will get all the words in the array
Next i
MsgBox(i) 'You will get the number of items in your array