I want to get my output from
223-F456
to
223-F456
223-F456#
223-F4560
223-#456
I've done simple code for this but only adding #,0 to the ends of lines works:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
For Each line In TextBox1.Lines
sb.AppendLine(line)
sb.AppendLine(line & "#")
sb.AppendLine(line & "0")
sb.Replace(line.LastIndexOf("-") + 1, "#") -> this doesn't work
Next
TextBox2.Text = sb.ToString
output:
223-F456
223-F456#
223-F4560
The letter is not always "F": I want to replace first letter after "-" not replace "F", also might some serials have "F" letter that not what I want.
Simple products serial in shop but replacing the string after "-" doesn't work and doesn't show, any help would be appreciated.
You can use String.Remove and String.Insert like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder()
For Each line In TextBox1.Lines
sb.AppendLine(line)
sb.AppendLine(line & "#")
sb.AppendLine(line & "0")
Dim replaceAt = line.LastIndexOf("-") + 1
sb.AppendLine(line.Remove(replaceAt, 1).Insert(replaceAt, "#"))
Next
TextBox2.Text = sb.ToString()
End Sub
Or if you preferred then you could use the String.Substring function:
sb.AppendLine(line.Substring(0, replaceAt) & "#" & line.Substring(replaceAt + 1))
It would also be possible to use a regular expression to do the replace, I expect someone else could come up with a better regex, but this works:
Dim re As New Regex("(.*-)([^-])(.*)")
For Each line In TextBox1.Lines
' ...
sb.AppendLine(re.Replace(line, "$1#$3"))
The problem is that
line.LastIndexOf("-") + 1
will return a number (indicating the place in line where it found the last - character, plus one).
But the replace function expects you to tell it what string you want to replace. You want to replace F, not a number. (Your current code would resolve to sb.Replace(4, "#"), which clearly won't find any 4s to replace.)
And if you do sb.Replace it'll replace it for all the versions of the string you've previously added to the stringbuilder. Therefore, it would make more sense to replace it in line, and then append that modified version of line to the stringbuilder.
sb.AppendLine(line.Replace("F", "#"))
Live demo: https://dotnetfiddle.net/5BZAUg
Edit:
If you need to replace any character following the -, not specifically an F, you can do it by finding the character index in line, and then removing the character at that index and replacing it with another one, e.g.
Dim index = line.LastIndexOf("-") + 1
sb.AppendLine(line.Remove(index, 1).Insert(index, "#"))
Demo: https://dotnetfiddle.net/RTbiUG
Related
I wonder if someone is able to help. I have a m3u file with multiple lines of formatted text.
#EXTM3U
#RADIOBROWSERUUID:963194ef-0601-11e8-ae97-52543be04c81
#EXTINF:1,80s80s Christmas
http://streams.80s80s.de/christmas/mp3-192/streams.80s80s.de/
#RADIOBROWSERUUID:9638cfa5-0601-11e8-ae97-52543be04c81
#EXTINF:1,181.FM - Christmas Kountry
http://www.181.fm/stream/pls/181-xkkountry.pls
Whilst I have managed to extract the data into a format that I can need... I am left with multiple blank lines. A sample bit of code I used to Extract the data is...
If line.StartsWith("#EXTM3U") Then 'Remove
lines(i) = ""
End If
If line.StartsWith("#RADIOBROWSERUUID:") Then 'Remove
lines(i) = ""
End If
If line.StartsWith("#EXTINF:1,") Then 'Add # at beginning of line
lines(i) = line.Replace("#EXTINF:1,", "#")
End If
Which then leaves me with the following...
#80s80s Christmas
#http://streams.80s80s.de/christmas/mp3-192/streams.80s80s.de/
#181.FM - Christmas Kountry
#http://www.181.fm/stream/pls/181-xkkountry.pls
I just dont seem to be able to remove the empty/blank lines. I have used google as well as here and non of the answers seem to work for me. Here is the code that I am using...
Dim Newlines As String() = File.ReadAllLines(ofd.FileName)
For t As Integer = 0 To Newlines.Length - 1
Dim line2 As String = Newlines(t)
If line2.StartsWith("") Then ' Remove blank lines
Beep()
Newlines(t) = line2.Replace(Environment.NewLine, String.Empty)
End If
Next
File.WriteAllLines("NewTextm3u.txt", lines)
Can any body see where I am going wrong? Thank you very much.
You can do this:
Dim sFile As String = "c:\test2\test2.txt"
Dim Fdata As New List(Of String)
Fdata = File.ReadAllLines("c:\test2\test.txt").ToList
For i = Fdata.Count - 1 To 0 Step -1
If Fdata(i) = "" Then
Fdata.RemoveAt(i)
End If
Next
For Each sLine As String In Fdata
Debug.Print(sLine)
Next
File.WriteAllLines(sFile)
The above would remove all blank lines
In place of that loop, you could also use lamda expression like this:
Fdata.RemoveAll(Function(MyOneRow) MyOneRow = "")
I used the StrignSplitOptions.RemoveEmptyEntries to get rid of blank lines.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim FileContents = File.ReadAllText("SomeFile.txt")
Dim lines = FileContents.Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
End Sub
As you can see in the above image, there is what we can call an "enter" at the end of the sentence and another one between.
So let's just remove the one between the sentences and because it's just a line you can do it like this:
If line(i) = CHR(13) & CHR(10) then line(i)=""
but if you want to get a little paranoid and just want to remove all the "enters" or "line breaks" just do it like this:
line(i)=Replace(line(i),CHR(13) & CHR(10),"")
I've been searching on internet how to Concatenate/Join Single quotes and comma on the String in vb.net's RichTextBox control. Example ('ABC','DEF','GHI,'JKL') I found this code online today it works even there's leading and trailing spaces and even lines are removed but the (' and ') are missing. Can you guys modify the code?
Code:
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim, "\s+", "','")
Inside the RichTextBox1
ABC
DEF
GHI
JKL
Result: ABC','DEF','GHI','JKL
Desired Result: ('ABC','DEF','GHI','JKL')
As you can see, there are multiple ways this could be done. Here's another:
myRichTextBox.Text = $"('{String.Join("'," & ControlsChars.Lf & "'", myRichTextBox.Lines)}')"
Note that I have used ControlChars.Lf where I would usually use Environment.NewLine because the RichTextBox always uses that line break. I assume that it has something to do with the RTF format and compatibility.
Give this a try
' starting RichTextBox1 contains
' ABC
' DEF
' GHI
' JKL
Dim lns() As String = RichTextBox1.Lines
For x As Integer = 0 To lns.Length - 1
lns(x) = String.Format("'{0}',", lns(x))
Next
lns(0) = "(" & lns(0)
lns(lns.Length - 1) = lns(lns.Length - 1).TrimEnd(","c)
lns(lns.Length - 1) &= ")"
RichTextBox1.Lines = lns
Not knowing how many lines you are dealing with in a real scenario, I chose to use a StringBuilder. It creates mutable (changeable) strings saving us throwing away and recreating strings many times.
Start off the sb with the initial "(". Then the loop uses an interpolated string with an embedded variable for each line. AppendLine will add a new line after the text.
Lastly we display the new string. In .net we can string the dot notation working left to right. First convert the StringBuilder back to an actual String with .ToString. Next we clean up the end of the new string by removing the final comma and the final new line. A new line is actually composed of 2 Chars, carriage return and line feed. Lastly I added the final ")"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines() = File.ReadAllLines("some text file path")
Dim sb As New StringBuilder
sb.Append("(")
For Each line In lines
sb.AppendLine($"'{line}',")
Next
RichTextBox1.Text = sb.ToString.Trim({","c, Convert.ToChar(13), Convert.ToChar(10)}) & ")"
End Sub
I have to prepare a school project of a Currency Converter in Visual Studio using Basic language.
I get the value of extange from XE website and it returns a string like "1.23454 GBP' So I need to remove most characters and numbers from it to have it as a Decimal, not String anymore so I can times it later in calculation.
I've tried to use .Remove anywhere and place it in textBox or Label but it didn't work.
Public Class receipt
Private Sub receipt_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim testString As String = "sadasdasd"
customername.Text = "Name: " + My.Settings.Username
Label6.Text = "Entered Money: " + My.Settings.inputamount + " " + My.Settings.currency
Label7.Text = "Converted To: " + My.Settings.outputamount
Label8.Text = "Charge: 0 (0%)"
TextBox1.Text = testString.Remove(4, 9)
End Sub
End Class
Screenshot of program running
Can someone help me to get this work?
Given your current input of "sadasdasd" and your expected return value then the call to string.Remove should be
TextBox1.Text = testString.Remove(3)
If you look at the MSDN documentation page of string.Remove you could see that the index is zero based so you want to remove anything starting from the fourth character that is at index 3 (keeps 0,1,2, removes from 3)
Also It seems that you think that the Remove second parameter is the end index where the Remove action should stop. But this is wrong, the second parameter is the number of characters to remove so 9 is not correct and probably gives you an ArgumentOutofRange Exception
I am attempting to write a program in VB.net which will output some values in to a text file. Please be patient with me as I am very new to VB.net.
What I have so far is below:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim str As String
For Each File As String In System.IO.Directory.GetFiles(TextBox1.Text)
str = str & File & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "||" & DateTimePicker1.Text & "|" & Environment.NewLine
Next
System.IO.File.WriteAllText("C:\output\output.txt", str)
End Sub
Results of output file (output.txt) when button3 is clicked are below:
C:\DirectoryTest\Clients\2356851-Kathy Winkler - Family Investments.pdf|2356851|2356851||04/10/2013|
C:\DirectoryTest\Clients\58736 -Katrina Armon - Sandlewood Homes Co.pdf|58736|58736||04/10/2013|
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|
My code so far does exactly what I want it to do, the only thing is that I want to make the code smarter but don’t know how. Smarter as in is there a way I can make the below code only pick up the 5 to 10 digit account number seen in the filename, and if no account number exists in the file name to bring up a message box?
System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim
As you can see from the last line of the output…
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|
…the customers name “Karen Cooper” is being displayed in both areas where the account number should be displayed. This is why I need to make this code smarter somehow have it search the file name for a 5 to 10 digit account number to display it after the file name as see in the other 2 examples.
Please let me know if this is possible. And do let me know if you have any questions.
Here is you some simple logic .... ofcouse you can just do something like finding the filename first but here you go
Dim returnval As String = ""
Dim s As String = "C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|"
For Each p As String In s
If IsNumeric(p) Then
returnval += p
Else
'MsgBox("no")
End If
Next
msgbox(returnval) will hold all your numbers 5-10 , depends on how specific you want to get from here
to break apart the filenames
'This will extract and return the filename from the specified path and filename.
'
Dim filePath As String = "c:\MyDirectory\MYFile.txt"
Dim slashPosition As Integer = filePath.LastIndexOf("\")
Dim filenameOnly As String = filePAth.Substring(slashPosition + 1)
MsgBox(filenameOnly)
*FOUND AT LINK http://www.vbforfree.com/274/extract-and-retrieve-the-filename-from-a-path/*
then manipulate your string from there as much as you want
You should give this a try. I haven't had a chance to test it but it should work
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim str As String
For Each File As String In System.IO.Directory.GetFiles(TextBox1.Text)
Dim strs as String() = System.IO.Path.GetFileNameWithoutExtension(File).Split("-")
Dim AccountNum as int = 0
For each section in strs()
' Loop through each section separated by - and try to cast it to an int
' you may want to use cLong instead
Try
AccountNum = cInt(section.trim())
exit for
Catch
End Try
Next
' DO LOGIC HERE TO BUILD OUTPUT with the account num now known
Next
System.IO.File.WriteAllText("C:\output\output.txt", str)
End Sub
How about yor file name ?
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf
Fairly, It should be
C:\DirectoryTest\Clients\001548 - Karen Cooper - Famtime.pdf
I would recommend using RegEx to extract the account number. A side benefit of using RegEx is that you can store the RegEx pattern outside of your code, such as in a configuration file, so if you ever need to modify the pattern, you could do so easily without recompiling your application.
Function GetAccountNumber(fileName As String) As String
Dim pattern As String = ".*?(?<acct>\d{5,10}).*?"
Dim regEx As New Regex(pattern)
Dim match As Match = regEx.Match(fileName)
Dim accountNumber As String = Nothing
If match.Success Then
Dim group As Group = match.Groups("acct")
If group.Success Then
accountNumber = group.Value
End If
End If
Return accountNumber
End Function
In the above example, I am using the following RegEx pattern to find the five to ten digit number in the string:
.*?(?<acct>\d{5,10}).*?
The .*? at the beginning and end of the pattern means any character, any number of times. The question mark means it's non-greedy. In other words, it only matches as many characters as necessary. By making it non-greedy, it will not steal-away any of the digits from the account number.
The parentheses surround the part of the string we are looking for (the account number). The ?<acct> at the beginning of the parenthetical group a name by which we can refer to it. In this case, I named the group acct. The \d means any digit character. The {5,10} means repeated between five and ten times.
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