I have a text file. I am reading all data from that text file. I have given code like this for removing all apostrophe and column, and double quotes, and comma.
sr = New StreamReader(Filename)
temp_data = sr.ReadLine
While Not temp_data = Nothing
'While sr.Peek() >= 0
sTemp = Split(temp_data, "|", -1)
Dim i As Integer
For i = 0 To sTemp.Length - 1
Replace(sTemp(i), ",", "")
Replace(sTemp(i), "'", "")
Replace(sTemp(i), """", "")
Next
Then I am assigning value like this:
POnum = Trim(sTemp(0))
POline = Trim(sTemp(1))
PORelnum = Trim(sTemp(2))
But still I am getting value with apostrophe. What is wrong with my code.
you have been trying to replace an array value within its scope.But it is easier to replace that value when it is assigned to a string and then it is assigned.here the code
Dim i As Integer = 0
Dim temp_data As String
Dim clean As String = String.Empty
While Not sr.EndOfStream
temp_data = reader.ReadLine()
Dim sTemp = temp_data .Split("|")
For Each j As String In sTemp
clean = j
clean = clean.Replace("'", "").Replace("""", "").Replace(",", "")
sTemp(i) = clean
i += 1
Next
End While
this will help you..
You are not saving the string that has the replaced text. Consequently it is lost. You should save it back in sTemp(i)
For i = 0 To sTemp.Length - 1
sTemp(i) = Replace(sTemp(i), ",", "")
sTemp(i) = Replace(sTemp(i), "'", "")
sTemp(i) = Replace(sTemp(i), """", "")
Next
However I think a better way would be to remove these characters before splitting so that there is no need to loop and remove from the array.
While Not temp_data = Nothing
temp_data = temp_data.Replace( ",", "").Replace( "'", "").Replace("""", "")
sTemp = Split(temp_data, "|", -1)
'-- no need to loop and replace now
This saves a lot of unnecessary code, isn't it?
Related
I have a list of accounts in a RichTextBox:
username:password|description
username1:password1|description
username3:password3|description3
username4:password5|description6
username1:password3|description5
username2:password4|description5
username2:password3|description3
The amount of rows in the list is arbitrary.
I want to remove the "|description" part of each row. Any suggestions?
Use a Regex
Dim rx As New System.Text.RegularExpressions.Regex("\|(.+)")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
This will remove any number of characters beginning with and including the pipe |. It will work with a RichTextBox having a Text property of any length (any number of rows).
If you want to leave just the password, you can do two replaces
Dim rx As New System.Text.RegularExpressions.Regex("\|(.+)")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
rx = New Regex("(.+):")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "")
Just remove anything up to and including the :
And just in case you ask, you could also remove the password with this
Dim rx As New System.Text.RegularExpressions.Regex(":(.+)\|")
RichTextBox1.Text = rx.Replace(RichTextBox1.Text, "|") ' or replace with ":"
Without regex?
Dim lines = RichTextBox1.Text.Split(vbLf)
Dim elements = lines.Select(Function(line) line.Split({":"c, "|"c}))
' password
RichTextBox1.Text = String.Join(vbLf, elements.Select(Function(element) element(1)))
' username:password
RichTextBox1.Text = String.Join(vbLf, elements.Select(Function(element) element(0) & ":" & element(1)))
' you get the idea
Spilt the text into an array then rewrite the items in the array to the text box
Dim arr1() As String=Split (rtb.Text,VbLf)
Dim finalstring As String= ""
For x As Integer=0 to Ubound(arr1) - 1
Dim arr2 () As String = Split (arr1 (x), "|")
finalstring += arr2 (0) & vbNewLine
Next
rtb.Text= finalstring
to show just the password; use the same technique as above
Dim arr1() As String=Split(rtb.Text,VbLf)
Dim finalstring As String= ""
For x As Integer = 0 to Ubound(arr1) - 1
Dim arr2 () As String = Split (arr1 (x), "|")
For x As Integer=0 to Ubound(arr2) - 1
Dim arr3 () As String = Split (arr2 (0), ":")
finalstring += arr3 (1) & vbNewLine
Next
Next
rtb.Text= finalstring
hello this is my firs thread ,
i'm trying to convert description of this page (https://www.tokopedia.com/indoislamicstore/cream-zaitun-arofah)
with regex and replace <br/> tag with new line and convert it to csv .
the datagridview it's alright but the csv got screwed
this is my code :
Dim dskrip As New System.Text.RegularExpressions.Regex("<p itemprop=""description"" class=""mt-20"">(.*?)\<\/p>\<\/div>")
Dim dskripm As MatchCollection = dskrip.Matches(rssourcecode0)
For Each itemdskrm As Match In dskripm
getdeskripsinew = itemdskrm.Groups(1).Value
Next
Dim deskripsinew As String = Replace(getdeskripsinew, ",", ";")
Dim deskripsitotal As String = Replace(deskripsinew, "<br/>", Environment.NewLine)
' ListView1.s = Environment.NewLine & deskripsinew
txtDeskripsi.Text = deskripsitotal
datascrapes.ColumnCount = 5
datascrapes.Columns(0).Name = "Title"
datascrapes.Columns(1).Name = "Price"
datascrapes.Columns(2).Name = "Deskripsi"
datascrapes.Columns(3).Name = "Gambar"
datascrapes.Columns(4).Name = "Total Produk"
Dim row As String() = New String() {getname, totalprice, deskripsitotal, directoryme + getfilename, "10"}
datascrapes.Rows.Add(row)
Dim filePath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Tokopedia_Upload.csv"
Dim delimeter As String = ","
Dim sb As New StringBuilder
For i As Integer = 0 To datascrapes.Rows.Count - 1
Dim array As String() = New String(datascrapes.Columns.Count - 1) {}
If i.Equals(0) Then
For j As Integer = 0 To datascrapes.Columns.Count - 1
array(j) = datascrapes.Columns(j).HeaderText
Next
sb.AppendLine(String.Join(delimeter, array))
End If
For j As Integer = 0 To datascrapes.Columns.Count - 1
If Not datascrapes.Rows(i).IsNewRow Then
array(j) = datascrapes(j, i).Value.ToString
End If
Next
If Not datascrapes.Rows(i).IsNewRow Then
sb.AppendLine(String.Join(delimeter, array))
End If
Next
File.WriteAllText(filePath, sb.ToString)
this is the csv file
I'm not sure where your problem is looking at the CSV file, but there are certain cases where you'll want to quote the values for a CSV. There's no official spec but RFC 4180 is often used as an unofficial standard. I would recommend using a library like CSV Helper
I create XML file from excel file. I save a string from one cell in a variable sObserved. When in that string I have a character "&" it should be replaced to "&"and when I have a character ";" it should be replaced to ";".
I use for this function Replace, this is my code:
sObserved = Replace(sObserved, "&", "&")
sObserved = Replace(sObserved, ";", ";")
But this can't work good, because when it will replace "&" on "&", the ";" will appear and next operation will change it to "&"
If I'll change an order it also will be wrong, because then sign "&" in ";" will be replaced.
Is there any possibility to replace it just like I wanted? I will be gratefull for any ideas because I stuck here.
Try this:
sObserved = Replace(sObserved, "&", "&")
sObserved = Replace(sObserved, ";", ";")
sObserved = Replace(sObserved, "&", "&")
This function is from http://www.codeproject.com/Articles/33064/VBScript-HTML-Encode. You may need to tweek it but it does a character by character check.
Function HTMLEncode(ByVal sVal)
sReturn = ""
If ((TypeName(sVal)="String") And (Not IsNull(sVal)) And (sVal<>"")) Then
For i = 1 To Len(sVal)
ch = Mid(sVal, i, 1)
Set oRE = New RegExp : oRE.Pattern = "[ a-zA-Z0-9]"
If (Not oRE.Test(ch)) Then
ch = "&#" & Asc(ch) & ";"
End If
sReturn = sReturn & ch
Set oRE = Nothing
Next
End If
HTMLEncode = sReturn
End Function
What you're after is a function to encode the output to be HTML friendly: htmlEncode. There are several scripts/functions around the web people have wrote, here is one:
' Encode an string so that it can be displayed correctly
' inside the browser.
'
' Same effect as the Server.HTMLEncode method in ASP
Function HTMLEncode(ByVal Text As String) As String
Dim i As Integer
Dim acode As Integer
Dim repl As String
HTMLEncode = Text
For i = Len(HTMLEncode) To 1 Step -1
acode = Asc(Mid$(HTMLEncode, i, 1))
Select Case acode
Case 32
repl = " "
Case 34
repl = """
Case 38
repl = "&"
Case 60
repl = "<"
Case 62
repl = ">"
Case 32 To 127
' don't touch alphanumeric chars
Case Else
repl = "&#" & CStr(acode) & ";"
End Select
If Len(repl) Then
HTMLEncode = Left$(HTMLEncode, i - 1) & repl & Mid$(HTMLEncode, _
i + 1)
repl = ""
End If
Next
End Function
ref: http://www.devx.com/vb2themax/Tip/19162
There is another here: http://www.codeproject.com/Articles/33064/VBScript-HTML-Encode
but that seems to encode everything that's not a character or letter. The regex in this one could probably be expanded a little better to include those that are ok for HTML.
Function HTMLEncode(ByVal sVal)
sReturn = ""
If ((TypeName(sVal)="String") And (Not IsNull(sVal)) And (sVal<>"")) Then
For i = 1 To Len(sVal)
ch = Mid(sVal, i, 1)
Set oRE = New RegExp : oRE.Pattern = "[ a-zA-Z0-9]"
If (Not oRE.Test(ch)) Then
ch = "&#" & Asc(ch) & ";"
End If
sReturn = sReturn & ch
Set oRE = Nothing
Next
End If
HTMLEncode = sReturn
End Function
How can I convert below string,
"[""1"",""2"",""3""]"
To this,
["1","2","3"]
I have try this without success:
Replace(string, """", "")
In vb.net - you should try like this,
Dim stringVar As String = "[""1"",""2"",""3""]"
stringVar.Replace("""", "")
Also check this to use Replace function.
If I understood correctly you can try something like this :
Dim s As String = "[""1"",""2"",""3""]"
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(s, "\d+")
Dim svals As String = ""
For Each m As System.Text.RegularExpressions.Match In collection
If svals = String.Empty Then
svals = m.Value
Else
svals = svals & "," & m.Value
End If
Next
Dim rr() As String
rr = svals.Split(",") ' Result as array of string
Demo
I'm writing the values of two (1 column) DGVs and a text box to a text file. The text box value is the heading, DGV1 is a column of strings (such as SI CA S C...etc) and DGV2 is a column of numbers of the format 11.23 or 0.01. The formats are exactly how I want them as displayed in the DGVs, but that formatting doesn't carry over to the text file these values are output to. Here's what I want the textfile to look like:
A012345 101 1.03
SI 32.13
C 1.45
CA 0.03
Here's what I'm getting instead:
A012345 101 1.03
SI32.13015
C1.452359
CA0.032568
Here's the code:
Try
Dim da, da2 As OleDbDataAdapter
Dim ds, ds2 As DataSet
'open connection to nit2.xlsm'
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & TextBox2.Text & """;Extended Properties=""Excel 12.0;HDR=YES;""")
'Fill dataviewgrid1 with element symbols, string, once'
da = New OleDbDataAdapter("select * from [Sheet1$A:A" & lastrow & "]", cn)
ds = New System.Data.DataSet
da.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
'''''''''''''loop through each sample and write to text file'''''''''''''''''''''''
da2 = New OleDbDataAdapter("select * from [Sheet1$B:B" & lastrow & "]", cn)
ds2 = New System.Data.DataSet
da2.Fill(ds2)
DataGridView2.DataSource = ds2.Tables(0)
'write sample heading to textbox1, looped'
TextBox1.Text = "Q0" & xlWsheet1.Cells(1, 2).Value & " " & xlWsheet2.Cells(1, 2).Value
'write to text file each data analysis point with formatted heading, looped'
Dim title As String = TextBox1.Text
Dim sub_title As String = title.Substring(0, 16)
Using writer As New System.IO.StreamWriter(fName, True)
writer.WriteLine(sub_title) 'heading'
Dim symbol, SymbolT As String
Dim compo As String
For cell1 As Integer = 0 To (DataGridView1.Rows.Count - 2)
symbol = Me.DataGridView1(0, cell1).Value 'element symbol'
symbolT = symbol.Trim
compo = Me.DataGridView2(0, cell1).Value 'composition'
writer.WriteLine(symbolT & compo)
Next
writer.Close()
End Using
cn.Close()
How can I format the numbers from DGV2 so that they only display to 2 decimals?
I also need to set the spacing between SI and 32.13 (for example) so that the decimal points in each line line up.
Formatting...anyone?
Something like this ?
Dim symbol As String
Dim compo As String
Dim symbolSpan As Integer = 0 ' stores the MaxLength of symbol
Dim compoSpan As Integer = 0 ' stores the Max Integer Part Length of compo
Dim symbolList As New List(Of String) ' all trimmed symbol
Dim compoList As New List(Of String) ' all trimmed compo
Dim compoIntLengthList As New List(Of Integer)
Dim doubleValue As Double
Dim i As Integer
Dim j As Integer
For i = 0 To (DataGridView1.Rows.Count - 2)
' element symbol...
symbol = Me.DataGridView1(0, i).Value.ToString().Trim()
symbolList.Add(symbol)
If symbol.Length > symbolSpan Then
symbolSpan = symbol.Length
End If
' composition...
If Double.TryParse(Me.DataGridView2(0, i).Value.ToString().Trim(), doubleValue) Then
compoList.Add(doubleValue.ToString("R"))
' well, the ToString("R") is not really the displayed value.
' if your DGV allows scientific display for Double then
' you'll have to handle that here with another code...
compo = doubleValue.ToString("F0") ' gets the Integer part length...
compoIntLengthList.add(compo.Length)
If compo.Length > compoSpan Then
compoSpan = compo.Length
End If
Else
' ohhhh ! the Cell doesn't contain a valid number... :/
compo = Me.DataGridView2(0, i).Value.ToString().Trim()
compoList.Add(compo)
If compo.Contains(".") Then ' Watch out culture about dots and commas...
If compoSpan < compo.IndexOf("."c) Then
compoSpan = compo.IndexOf("."c)
End If
compoIntLengthList.add(compo.IndexOf("."c))
Else
If compoSpan < compo.Length Then
compoSpan = compo.Length
End If
compoIntLengthList.add(compo.Length)
End If
End If
Next
symbolSpan = symbolSpan + 1 ' space between symbol and compo.
Using writer As New System.IO.StreamWriter(fName, True)
writer.WriteLine(sub_title) 'heading'
For i = 0 To symbolList.Count - 1
symbol = symbolList.Item(i)
While symbol.Length < symbolSpan
symbol = symbol + " "
End While
compo = compoList.Item(i)
j = compoIntLengthList.Item(i)
While j < compoSpan
compo = " " + compo
j = j + 1 ' this is what was causing the endless loop.
End While
writer.WriteLine(symbol & compo)
Next
symbolList.Clear()
symbolList= Nothing
compoList.Clear()
compoList = Nothing
compoIntLengthList.Clear()
compoIntLengthList = Nothing
writer.Close()
End Using
I haven't tested the code. Just written it on the fly.. The approach looks ugly (and I agree) but that's one way I remember so far. Could be better with String.Format or StringBuilder I guess but don't remember well how those ones works, sorry.
EDIT : Missed the two decimals part...
Oh, sorry ! You want only two decimals.. Replace this :
compoList.Add(doubleValue.ToString("R"))
by this :
compoList.Add(doubleValue.ToString("F2"))
' or this :
compoList.Add(doubleValue.ToString("#.##")) ' to allow 0 or 1 decimal aswell
and replace this part :
' ohhhh ! the Cell doesn't contain a valid number... :/
compo = Me.DataGridView2(0, i).Value.ToString().Trim()
compoList.Add(compo)
If compo.Contains(".") Then ' Watch out culture about dots and commas...
If compoSpan < compo.IndexOf("."c) Then
compoSpan = compo.IndexOf("."c)
End If
compoIntLengthList.add(compo.IndexOf("."c))
Else
If compoSpan < compo.Length Then
compoSpan = compo.Length
End If
compoIntLengthList.add(compo.Length)
End If
by this :
' ohhhh ! the Cell doesn't contain a valid number... :/
compo = Me.DataGridView2(0, i).Value.ToString().Trim()
If compo.Contains(".") Then ' Watch out culture about dots and commas...
If compoSpan < compo.IndexOf("."c) Then
compoSpan = compo.IndexOf("."c)
End If
If compo.Length > (compo.IndexOf("."c) + 3) Then
compo = compo.SubString(0, compo.IndexOf("."c) + 3)
End If
compoIntLengthList.add(compo.IndexOf("."c))
Else
If compoSpan < compo.Length Then
compoSpan = compo.Length
End If
compoIntLengthList.add(compo.Length)
End If
compoList.Add(compo)