I have in a text file lines of this format:
word1|word2|word3
anotherword1|anotherword2
I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3
Here is what I have so far:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
For Each line As String In File.ReadLines("C:\text.txt")
Dim input As String = line
Dim result As String() = line.Split(New String() {"|"}, StringSplitOptions.None)
For Each s As String In result
Try
Dim linex As String = line
RichTextBox1.Text = RichTextBox1.Text.Replace(s, " " & linex)
Catch exxx As Exception
End Try
Next
Next
End Sub
It works great, but after the replacement, the replaced text still have the detected word and it keep replacing itself with word1|word2|word3 forever. And I want do do the process just once.
Like this: Click to see
Due to the format the words are stored in, it will be much easier to achieve what you want using Regular Expressions:
Dim lines = File.ReadLines("C:\text.txt")
For Each line As String In lines
Dim pat = String.Format("\b({0})\b", line)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, pat, line)
Next
This should do pretty much what you want.
Check it here.
Related
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text ^ 2
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
TextBox1.Text = Nothing
TextBox2.Text = Nothing
End Sub
End Class
The code above outputs squares of any single values input in textbox1 but i need some help in inputting a couple of values separated by commas and then output the squares of those individual values eg 3,4 the output 9,16
I'm not going to do it all for you, because this looks like homework, but here are some pointers:
TextBox2.Text = TextBox1.Text ^ 2
1) Turn on Option Strict, by placing Option Strict On at the top of your code file or by putting it in the project properties Compile tab. This will help you be more rigorous with your coding. Here you're taking a string (TextBox1.Text) and having VB auto convert it to a number (which might fail), squaring it, and then auto converting it back to a string to store in TextBox2.Text. This is bad news all round; always be crystal clear in your own mind and explicit in your coding about the difference between various data types.A string containing numbers is not the same thing as a number!
2) Rename your textboxes after you drop them on a form. Nothing is more frustrating than to read a block of code where the variable names are irrelevant garbage. You will find this when you come back to some complex code in 6 months and think "what the..."; renaming a textbox so it is called resultTextBox or inputTextBox takes seconds and makes your code instantly more comprehensible to both you and anyone you call in to help out with it
separated by commas
The following line of code will split a string into an array of strings, on comma:
Dim csv = "3,6"
Dim arr = csv.Split(","c)
Console.WriteLine(arr(0)) 'prints 3
Console.WriteLine(arr(1)) 'prints 6
The following line of code will convert a string to an integer:
Dim s = "3"
Dim i = Convert.ToInt32(s)
Maths operations can now be performed on it
i = i * i 'square it
The following line of code will turn an integer into a string:
Dim i as Integer = 3
Dim s as String = i.ToString() 's is now "3"
The following line of code will loop through an array, appending the values in the array to a string variable, and adding commas. Finally it trims off the excess trailing comma
Dim s as New String
For Each x as String in arr
s = s & x & ","
Next x
s = s.TrimEnd(","c)
Here is another way too, using the String.Join helper method:
Dim s as String = String.Join(","c, arr)
I need to extract text from a text file starting with the order number(eg. Order1) and ending with an empty line with all other lines between the order number and the empty line extracted as well for a query. Really have no idea how to go about this so any help is greatly appreciated!
so the file name is "CustomerDetails.txt" and I'd imagine the code would look something like this
If IO.File.Exists("CustomerDetails.txt") Then
Dim inFile As IO.StreamReader = IO.File.OpenText(“CustomerDetails.txt")
End If
and then taking for example "order1" in that text file until the blank space and displaying that is a list box
"Really have no idea how to go about this "
The thinking could go like this...
A text file has a string in it.
I could look up the String class in .net and see if there are any methods that could help me.
Search for "String class in .net"
Looks like we can use a combination of String.IndexOf(String, Int32) and String.Substring(Int32, Int32)
Find the IndexOf your order. The string will be the order "Order1" and we will start looking at index 0 so the Int32 will be 0. Then find the end index. Start looking at the index we just found and stop at the first blank line. We can get the length required by the `.Substring method by subtracting the start index from the end index. Now we can extract the text of Order 1 with the substring method.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OrderText As String = "Order 1" 'this could be set with TextBox1.Text
'Get the string out of the file
Dim s As String = File.ReadAllText("CustomerDetails.txt")
'Find the index of the order, this overload assumes start index is 0
Dim startIndex As Integer = s.IndexOf(OrderText) 'starts lookint at beginning
'Find the index of the first blank line after the startIndex
'2 new lines make a bland line
Dim endIndex As Integer = s.IndexOf(Environment.NewLine & Environment.NewLine, startIndex)
'Return the string that stars at startIndex with a length of end minus start
Dim Order As String = s.Substring(startIndex, endIndex - startIndex)
'I am going to guess that the details of the order are on separate lines
Dim lines() As String = Order.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
ListBox1.Items.Add(line)
Next
End Sub
I also want to display the line containing the word. I want to open an external .txt file and delete any line if it contains a specific string. I have a search and replace at the moment for one word but want the entire line to be removed from the file. Thanks
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamReaderL1 As System.IO.StreamReader
Dim myStream As System.IO.StreamWriter
Dim myStr As String
myStreamReaderL1 = System.IO.File.OpenText("C:\Users\f1r1a\Desktop\memes.txt")
myStr = myStreamReaderL1.ReadToEnd()
myStreamReaderL1.Close()
myStr = myStr.Substring("fraser", 6)
'Save myStr
myStream = System.IO.File.CreateText("C:\Users\f1r1a\Desktop\memes.txt")
myStream.WriteLine(myStr)
myStream.Close()
End Sub
Well you can do all of that code in two lines
Dim result = File.ReadLines("C:\Users\f1r1a\Desktop\memes.txt").
Where(Function(x) Not x.Contains("fraser"))
File.WriteAllLines("C:\Users\f1r1a\Desktop\memes.txt", result.ToArray)
The IEnumerable extension Where receives, line by line, the sequence produced by File.ReadLines. Each line is processed by Where applying the Contains method and if the line doesn't contains the word searched then it is passed as output to the result variable. In turn the result variable is passed as an array to the WriteAllLines method.
You can get both at once:
Dim file = "C:\Users\f1r1a\Desktop\memes.txt"
Dim lookup = File.ReadLines(file).ToLookup(Function(l) l.Contains("fraser"))
textBoxRemoved.Text = String.Join("|", lookup(True))
File.WriteAllLines(file, lookup(False))
i'm in the making of machine readable dictionary for my native language which is Malay. i need to extract the Malay translation from the .txt file. In the .txt file, the example are like this:
aberration : aberasi
aberration function : rangkap aberasi
ablation : ablasi
ablative material : bahan ablasi
the left one are the terms in English and after the separator : is Malay.
What I would like to ask is how do i do when the word search is "aberration function" and i need to display only "rangkap aberasi"?
i tried to used
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim text As String = "dictionary.txt"
Dim word As String = "\b" & TextBox2.Text & "\b\s+(\w+)"
For Each a As Match In Regex.Matches(text, word, RegexOptions.IgnoreCase)
MsgBox(a.Groups(1).Value)
Next
End Sub
End Class
See more at: http://www.visual-basic-tutorials.com/get-the-next-word-after-a-specific-word-in-visual-basic.htm#sthash.w8E1Qb6l.dpuf
however, my problem is, this code above only display the next word after seperation which is "rangkap". while i need the whole text after separation ":" which might be more than 2 words.
here is my current code
Using reader As New StreamReader("D:\Dictionary of Engineering A only.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(wordsearch.Text) Then
Edef.Text = line
Exit While
End If
End While
End Using
One way to solve this would be like this:
Using reader As New StreamReader("D:\Dictionary of Engineering A only.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(wordsearch.Text) Then
dim lineParts() as String = line.split(":")
Edef.Text = lineParts(1)
Exit While
End If
End While
End Using
You check if the line contains the text, if so, you split the line by the ":" and take the 2nd part of it.
start=AKS-RHzlSXSftLGYdBNk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1&
For every instance of the word 'start' I need to be able to get the text after the first full stop, right up until the & symbol. E.g. 'eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1'.
There will be more than one instance of this. They will need to be appended to a listbox.
What is the simplest/quickest way to do this? (Using possibly streamreader - text file)
The simplest and quickest way will be to read each line, and check if it .StartsWith("start="). If so, then get the .IndexOf(".") and the .IndexOf("&", <whereever the first indexOf was>). Get the .SubString which encompasses those two values. I'm sure you can write the code yourself from that ;)
I tested this function with a button click, output text each line on a textbox. I am sure you can adapt this to your code.
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtResults.Text = ""
Dim ParseString As String
ParseString = "start=123341.23124&kjdshfkjsdaksdstart=1231.2321312&kadhskjashdkjastart=1231.23126789898&skjdfhkjsd"
Dim Delimiters() As String = New String() {"start="}
Dim Words() As String
Words = ParseString.Split(Delimiters, CompareMethod.Text)
For Each Part In Words
Dim Middle As String
Middle = Part.Split(".").Skip(1).Take(1).FirstOrDefault()
Dim Good As String
Good = Middle.Split("&").FirstOrDefault()
txtResults.Text += Good + vbNewLine
Next
End Sub
Output was
23124
2321312
23126789898
Added 31104 lines to a string and ran, took about 11 seconds to run on my laptop. Might be too slow for your app?