Search for keywords send preceeding text to specific textboxes vb.net - vb.net

I have a txt text file in that I have a few lines as follows:
SW1:bla bla bla
SW2:yada yada yada
SW3:yak yak yak
I would like vb net to look for the line SW1: and place whatever preceeds in textbox1
like wise sw2: in textbox2, and SW3: in textbox 3:
all the remaining lines go in rich textbox1
is it possible to search for key words and send the preceeding text to specific textboxes ussing vb.net?

You can usee File.ReadAllLines to load the entire file into an array of strings (one item per line in the file). Then, you can use the String.StartsWith and String.SubString methods to parse each line, for instance:
For Each line As String In File.ReadAllLines(filePath)
If line.StartsWith("SW1:") Then
TextBox1.Text = line.SubString(4)
End If
'...
Next
Alternatively, if all the keywords are the same length, you could use a select case:
For Each line As String In File.ReadAllLines(filePath)
Select Case line.SubString(0, 4)
Case "SW1:"
TextBox1.Text = line.SubString(4)
' ...
End Select
Next
Or, if all the keywords end with a colon, and none of the values contain that character, you could use String.Split to split the key/value pair from each line:
For Each line As String In File.ReadAllLines(filePath)
Dim parts() As String = line.Split(":"c)
Select Case parts(0)
Case "SW1"
TextBox1.Text = parts(1)
' ...
End Select
Next
To read the rest of the file into a rich text box, there are multiple ways you could do that, but one of the simplest ways would be like this:
Dim builder As New StringBuilder()
For Each line As String In File.ReadAllLines(filePath)
If line.StartsWith("SW1:") Then
TextBox1.Text = line.SubString(4)
Else If line.StartsWith("SW2:") Then
TextBox2.Text = line.SubString(4)
Else If line.StartsWith("SW3:") Then
TextBox3.Text = line.SubString(4)
Else
builder.AppendLine(line)
End If
Next
RichTextBox1.Text = builder.ToString()

Since Mr. Steven already got the answer. You can also use like this,.
Dim source = File.ReadAllLines("d:\source.txt")
sw1TextBox.Text = source.Where(Function(c) c.StartsWith("SW1:")).FirstOrDefault().Substring(4)
sw2TextBox.Text = source.Where(Function(c) c.StartsWith("SW2:")).FirstOrDefault().Substring(4)
sw3TextBox.Text = source.Where(Function(c) c.StartsWith("SW3:")).FirstOrDefault().Substring(4)

Related

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

VB.net removing and keeping words in a textbox

[{"name":"chrisjj","uuid":"d086112c-6e25-31a0-acf0-f95c3ca98784","expiresOn":"2016-02-22 23:04:35 +0000"}]
[{"name":"ben","uuid":"d086112c-7a26-33b5-ucf3-j96c1ca26854","expiresOn":"2015-011-12 22:04:35 +0000"}]
Basically im working on a project for a while now and I am trying to keep the names chrisjj and ben and removing the rest of the text from textbox in visual basic 2012 if you have any idea that would be great help
You may use regex to achieve what you want.
Dim Input As String = RichTextBox1.Text
Dim MC As MatchCollection = Regex.Matches(Input, Regex.Escape("[{""name"":""") & "[chrisjj|ben].*?" & Regex.Escape("]"), RegexOptions.IgnoreCase)
Dim Output As New List(Of String)
For i = 0 To MC.Count - 1
Output.Add(MC(i).Value)
Next
MsgBox(String.Join(vbNewLine, Output.ToArray()))
I think this is what you want. this regex matches [{"name":" then chrisjj or ben and goes on until ] is found.
You can do this:
If InStr(Textbox1.Text, "chrisjj") Then
Textbox1.text = "chrisjj"
else if InStr(Textbox1.Text, "ben") Then
Textbox1.text = "ben"
end if
The InStr Function returns the position of the first occurrence of one string within another.
Also
if TextBox1.Text.Contains("chrisjj") Then
TextBox1.Text = TextBox1.Text = "chrisjj"
ElseIf TextBox2.Text.Contains("ben") Then
TextBox1.Text = TextBox1.Text = ben
end if
The String.Contains Method (String) returns a value indicating whether a specified substring occurs within this string.

How do I manipulate the last string of a Richtextbox in Visual Basic

I am trying to take a string in a rich text box and replace them with a different string.
Now how this should work is that if two same characters are entered into the text box
e.g tt the "tt" will be replaced with "Ǿt" , it adds back one of the t's to the replaced string. Only the most recently entered string is manipulated if two same characters are entered .
I read the LAST string that is in the RichTextBox by using this method
Dim laststring As String = RichTextBox1.Text.Split(" ").Last
'hitting space bar breaks the operation so if i enter t t there will be no replacement
this is the replacement method which I use , it works correctly .
if laststring = "tt"
RichTextBox1 .Text = RichTextBox1 .Text.Replace("tt", "Ǿt")
This method is inefficient because i need to check id there are double letters for all letters and if i was to use this method it would tavke up a lot of code .
how can I accomplish this using a shorter method??
You need to put the if then section in a loop.
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
For Each item As String In doubleinstance
If RichTextBox1.Text.EndsWith(item) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" & holdstring)
MsgBox(curstring)
End If
Next item
Here's a bit of code to get you in the right direction...
There are a couple of variations of .Find, but you probably want to look at the .Select method.
With RichTextBox1
.Find("Don")
.SelectedText = "Mr. Awesome"
End With
Here is a way I came up with
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
If curstring = doubleinstance(0) And RichTextBox1.Text.EndsWith(doubleinstance(0)) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" + holdstring)
MsgBox(curstring)
End If
where i have doubleinstance(0) how do i get the if statement to not only check a single index but all of the index from 0 to 2 in this example ?

Get only the line of text that contains the given word VB2010.net

I have a text file on my website and I download the whole string via webclient.downloadstring.
The text file contains this :
cookies,dishes,candy,(new line)
back,forward,refresh,(new line)
mail,media,mute,
This is just an example it's not the actual string , but it will do for help purposes.
What I want is I want to download the whole string , find the line that contains the word that was entered by the user in a textbox, get that line into a string, then I want to use the string.split with as delimiter the "," and output each word that is in the string into an richtextbox.
Now here is the code that I have used (some fields are removed for privacy reasons).
If TextBox1.TextLength > 0 Then
words = web.DownloadString("webadress here")
If words.Contains(TextBox1.Text) Then
'retrieval code here
Dim length As Integer = TextBox1.TextLength
Dim word As String
word = words.Substring(length + 1) // the plus 1 is for the ","
Dim cred() As String
cred = word.Split(",")
RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
Else
MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
End If
Else
MsgBox("Please fill in an word", MsgBoxStyle.Critical)
End If
Now it works and no errors , but it only works for line 1 and not on line 2 or 3
what am I doing wrong ?
It's because the string words also contains the new line characters that you seem to be omitting in your code. You should first split words with the delimiter \n (or \r\n, depending on the platform), like this:
Dim lines() As String = words.Split("\n")
After that, you have an array of strings, each element representing a single line. Loop it through like this:
For Each line As String In lines
If line.Contains(TextBox1.Text) Then
'retrieval code here
End If
Next
Smi's answer is correct, but since you're using VB you need to split on vbNewLine. \n and \r are for use in C#. I get tripped up by that a lot.
Another way to do this is to use regular expressions. A regular expression match can both find the word you want and return the line that contains it in a single step.
Barely tested sample below. I couldn't quite figure out if your code was doing what you said it should be doing so I improvised based on your description.
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click
Dim downloadedString As String
downloadedString = "cookies,dishes,candy," _
& vbNewLine & "back,forward,refresh," _
& vbNewLine & "mail,media,mute,"
'Use the regular expression anchor characters (^$) to match a line that contains the given text.
Dim wordToFind As String = TextBox1.Text & "," 'Include the comma that comes after each word to avoid partial matches.
Dim pattern As String = "^.*" & wordToFind & ".*$"
Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)
Dim M As Match = rx.Match(downloadedString)
'M will either be Match.Empty (no matching word was found),
'or it will be the matching line.
If M IsNot Match.Empty Then
Dim words() As String = M.Value.Split(","c)
RichTextBox1.Clear()
For Each word As String In words
If Not String.IsNullOrEmpty(word) Then
RichTextBox1.AppendText(word & vbNewLine)
End If
Next
Else
RichTextBox1.Text = "No match found."
End If
End Sub
End Class

Search field in text file

I have some coding which displays a label if the value of a textbox matches any of the first values of each line in a textfile.
Dim sList As New List(Of String)(IO.File.ReadAllLines("Path"))
Dim i As Integer
For i = 0 To sList.Count - 1
If sList(i).StartsWith(textbox1.Text) Then
Label1.Visible = True
Exit For
Else
Label1.Visible = False
End If
Next
The problem is if the textbox has 1 and the textfile has 11 it will display the label, what would be the best way around this?
I have tried sList(i).Contains etc but none of them are doing the job.
I have tried all the suggestions here and nothing works, my textfile has numbers like the following
11
15
18
and for example if i have the number 1 in the textbox then the label is visible.
Try this:
Label1.Visible = IO.File.ReadAllLines("Path.txt").Any(Function(f) f = TextBox1.Text)
I think LINQ can be used here:
Dim text = textbox1.Text
Dim textWithSpace = String.Format("{0} ", text)
Label1.Visible = IO.File.ReadAllLines("Path").Any(Function(line) line.StartsWith(textWithSpace) OrElse line = text)
You need import System.Linq to make it work.
I assumed that space ends each word in the file.
If you want the Label to be visible when at least one of the lines starts with the text in the TextBox, you can use LINQ and Enumerable.Any:
Dim matchingLines = From l In IO.File.ReadLines("Path")
Where l.StartsWith(textbox1.Text)
Label1.Visible = matchingLines.Any()
Try changing the following line, assuming you are reading from a text file and looking for an exact match of the whole line you could try this:
If sList(i).StartsWith(textbox1.Text + Environment.NewLine) Then
That should check to make sure its the only thing on that line as it is now looking for a new line and will not match '11'