Related
I have the a string in below format
Dim str as String = "[1_5],[1_3],[1_5]"
The part before the _ can be variable is not a fix number
i need to convert it in to format
"5,3,5"
i have used the below code to obtain all the number that i need in the new string in the matches Item Groups
Dim pattern As String = "_(.*?)\]"
Dim matches As MatchCollection =
Regex.Matches(rowpanel.getRequestedArea_selectionArea(), pattern, RegexOptions.Singleline)
My question is how i can join all the Groups to obtain the final string format ?
A Regex solution could be
Dim x = matches.Select(Function(g) g.Groups(1).Value)
Dim final = String.Join(",", x)
A Split and Join one is
Dim blocks As String() = str.Split(",")
Dim result = New List(Of String)()
For Each s In blocks
result.Add(s.Split("_")(1).Trim("]"))
Next
Dim final = String.Join(",", result)
You can do something like this using RegEx and replace:
Dim str As String = "[1_5],[1_3],[1_5]"
Dim RegX As Regex = New Regex("\[\d{1}_")
Dim match As Match = RegX.Match(str)
If match.Success Then
str = Replace(str, match.Value, "")
str = Replace(str, "]", "")
End If
Alternative with simple and readable loop but multiple lines of code wrapped with a method
Public Function ExtractNumbers(text As String) As String
Dim current As New StringBuilder()
Dim write As Boolean = False
For Each character As Char In text
If character = "_"c Then
write = True
Continue For
End If
If character = "]"c Then
write = False
current.Append(",")
Continue For
End If
If write Then
current.Append(character)
Continue For
End If
Next
current.Length -= 1
Return current.ToString()
End Function
Usage
var extracted = ExtractNumbers("[1_5],[1_3],[1_5]")
Console.WriteLine(extracted)
' 5,3,5
Can i make little short that code? I would not like to write this too many times, so I would like to make it shorter. just for the first 5, i don't want for all the lines of the textbox.
str2 = TxtBoxIntDraws1.Lines(0)
Dim strWords2 As String() = str2.Split(",")
str3 = TxtBoxIntDraws1.Lines(1)
Dim strWords3 As String() = str3.Split(",")
str4 = TxtBoxIntDraws1.Lines(2)
Dim strWords4 As String() = str4.Split(",")
str5 = TxtBoxIntDraws1.Lines(3)
Dim strWords5 As String() = str5.Split(",")
str6 = TxtBoxIntDraws1.Lines(4)
Dim strWords6 As String() = str6.Split(",")
You can do like following
For idx = 0 To 4
str = TxtBoxIntDraws1.Lines(idx)
Dim strWords As String() = str.Split(",")
Next idx
If you want to process the split words later you can save the data to an array and process later.
Follow the following code for this.
Dim idx As Integer
Dim strWords(5)() As String
For idx = 0 To 4
str = TxtBoxIntDraws1.Lines(idx)
strWords(idx) = str.Split(",")
Next idx
' process strWords
Paraphrase of the answer by Vignesh Kumar A. This will give you lines 1 - 4. The index starts at zero.
Private Sub OPCode()
Dim blankList As New List(Of String())
For i = 0 To 3
blankList.Add(TextBox1.Lines(i).Split(","c))
Next
End Sub
i have this string
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
and want to retrieve a string
newstr = 12,32,15,16,14
i tried this much
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim word As String
Dim uc As String() = test.Split(New Char() {","c})
For Each word In uc
' What can i do here?????????
Next
only unique numbers how can i do that in vb asp.net
right answer
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim word As String
Dim uc As String() = test.Split(New Char() {","c}).Distinct.ToArray
Dim sb2 As String = "-1"
For Each word In uc
sb2 = sb2 + "," + word
Next
MsgBox(sb2.ToString)
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim uniqueList As String() = test.Split(New Char() {","c}).Distinct().ToArray()
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
'Split into an array
Dim testArray As String() = test.Split(",")
'remove duplicates
Dim uniqueTestArray As String() = testArray.Distinct().ToArray())
'Concatenate back to string
Dim uniqueString As String = String.Join(",", uniqueTestArray)
Or all in one line:
Dim uniqueString As String = String.Join(",", test.Split(",").Distinct().ToArray())
Updated Sorry I forgot to add the new string together
Solution:
Dim test As String = "12,32,12,32,12,12,32,15,16,15,14,12,32"
Dim distinctArray = test.Split(",").Distinct()
Dim newStr As String = String.Join(",", distinctArray.ToArray())
Training References: Check out this website for a guide on LINQ which will make these types of programming challenges easier for you. LINQ Tutorial
You forgot to put parentheses for Distinctand ToArray. Because these are methods
Dim uc As String() = test.Split(New Char() {","c}).Distinct().ToArray()
I have following code and it's slow to load first time. CSV file is about 4mb 16000 rows.
If Session("tb") Is Nothing Then
Dim str As String()
If (IsNothing(Cache("csvdata"))) Then
str = File.ReadAllLines(Server.MapPath("~/test/feed.csv"))
Cache.Insert("csvdata", str, Nothing, DateTime.Now.AddHours(12), TimeSpan.Zero)
Else
str = CType(Cache("csvdata"), Array)
End If
Dim dt As New DataTable
dt.Columns.Add("Shape", GetType(System.String))
dt.Columns.Add("Weight", GetType(System.Double))
dt.Columns.Add("Color", GetType(System.String))
dt.Columns.Add("Clarity", GetType(System.String))
dt.Columns.Add("Price", GetType(System.Int32))
dt.Columns.Add("CutGrade", GetType(System.String))
For i As Integer = 1 To str.Length - 1
Dim pattern As String = ",(?=([^""]*""[^""]*"")*[^""]*$)"
Dim rgx As New Regex(pattern)
Dim t As String = rgx.Replace(str(i), "\")
Dim s As String() = t.Split("\"c)
Dim pr As Int32 = CType(s(5), Int32)
Dim fpr As Int32
Dim rate As Double
Select Case pr
Case Is < 300
rate = 2
Case 301 To 600
rate = 1.7
Case Is > 600
rate = 1.16
End Select
fpr = Math.Round(pr * rate)
Dim a As String() = {s(1), s(2), s(3), s(4), fpr, s(40)}
dt.Rows.Add(a)
Next
Session("tb") = dt
ListView1.DataSource = dt
ListView1.DataBind()
Else
Dim x As DataTable = CType(Session("tb"), DataTable)
ListView1.DataSource = x
ListView1.DataBind()
End If
csv file is cached and I assume this can share with everyone.
(one person loads once in 12 hours)
Once I create Session, the page loads fast as well.
So, creating Datatable seems to be the slow process.
This is first time to deal with datatable and I'm sure someone can point out what I'm doing wrong.
Thank you
UPDATE:
I have changed Cache to the original Datatable instead of CSV file.
It loads fast now, but I would like to know if this is a bad idea or not.
Cache.Insert("csvdata", dt, Nothing, DateTime.Now.AddHours(12), TimeSpan.Zero)
Once it's stored in Cache, I can run Query against it using Linq.
SAMPLE CSV first 3 rows
Supplier ID,Shape,Weight,Color,Clarity,Price / Carat,Lot Number,Stock Number,Lab,Cert #,Certificate Image,2nd Image,Dimension,Depth %,Table %,Crown Angle,Crown %,Pavilion Angle,Pavilion %,Girdle Thinnest,Girdle Thickest,Girdle %,Culet Size,Culet Condition,Polish,Symmetry,Fluor Color,Fluor Intensity,Enhancements,Remarks,Availability,Is Active,FC-Main Body,FC- Intensity,FC- Overtone,Matched Pair,Separable,Matching Stock #,Pavilion,Syndication,Cut Grade,External Url
9349,Round,1.74,F,VVS1,13650.00,,IM-95-188-243,ABC,11228,,,7.81|7.85|4.62,59.00,62.00,34.00,13.00,,,Medium,,0,None,,Excellent,Very Good,Blue,Medium,,"",Not Specified,Y,,,,False,True,,,,Very Good,http://www.test/teste.
9949,Round,1.00,I,VVS1,6059.00,,IM-95-189-C021,ABC,212197,,,6.37|6.42|3.96,61.90,54.00,34.50,16.00,,,Thin,Slightly Thick,0,None,,Excellent,Good,,None,,"Additional pinpoints are not shown.",Guaranteed Available,Y,,,,False,True,,,,Very Good,http://www.test/test.
Look into using a TextFieldParser to read the CSV instead of splitting the strings yourself.
Also, if you use a List(Of CustomClass) where CustomClass has the Shape, Weight, Color, etc. properties you can avoid the unnecessary overhead of the DataTable and you can still do your LINQ queries against the List.
Pardon my C#, I do not have VB.NET installed on this box.
public class Gemstone
{
public string Shape { get; set; }
public double Weight { get; set; }
public string Color { get; set; }
}
static void Main(string[] args)
{
TextFieldParser textFieldParser = new TextFieldParser("data.txt");
textFieldParser.Delimiters = new string[] {","};
textFieldParser.ReadLine(); // skip header line
List<Gemstone> list = new List<Gemstone>(16000); // allocate the list with your best calculated guess of its final size
while(!textFieldParser.EndOfData)
{
string[] fields = textFieldParser.ReadFields();
Gemstone gemstone = new Gemstone();
gemstone.Shape = fields[1];
gemstone.Weight = Double.Parse(fields[2]);
gemstone.Color = fields[3];
list.Add(gemstone);
}
FYI I just found this whole TextFieldParser thing, and I do a LOT of text file parsing so I tested it....
On an 11mb file, with about 5200 rows and 300 columns.
It was 25% of the speed i was using when putting in a datatable. It was about 15% of the speed when I removed the datatable code:
Dim DataTable As New DataTable()
Dim StartTime As Long = Now.Ticks
Dim Reader As New FileIO.TextFieldParser("file.txt")
Reader.TextFieldType = FileIO.FieldType.Delimited
Reader.SetDelimiters(vbTab)
Reader.HasFieldsEnclosedInQuotes = False
Dim Header As Boolean = True
While Not Reader.EndOfData
Dim Fields() As String = Reader.ReadFields
If Header Then
For I As Integer = 1 To 320
DataTable.Columns.Add("Col" & I)
Next
Header = False
Else
If Mid(Fields(0), 1, 1) <> "#" Then DataTable.Rows.Add(Fields)
End If
End While
Debug.Print((Now.Ticks - StartTime) / 10000 & "ms")
Dim DataTable2 As New DataTable()
StartTime = Now.Ticks
For I As Integer = 1 To 320
DataTable2.Columns.Add("Col" & I)
Next
For Each line As String In System.IO.File.ReadAllLines("file.txt")
Dim NVP() As String = Split(line, vbTab)
If Mid(line, 1, 1) <> "#" Then DataTable2.Rows.Add(NVP)
Next
Debug.Print((Now.Ticks - StartTime) / 10000 & "ms")
With the datable code removed:
Dim StartTime As Long = Now.Ticks
Dim Reader As New FileIO.TextFieldParser("file.txt")
Reader.TextFieldType = FileIO.FieldType.Delimited
Reader.SetDelimiters(vbTab)
Reader.HasFieldsEnclosedInQuotes = False
Dim Header As Boolean = True
While Not Reader.EndOfData
Dim Fields() As String = Reader.ReadFields
End While
Debug.Print((Now.Ticks - StartTime) / 10000 & "ms")
StartTime = Now.Ticks
For Each line As String In System.IO.File.ReadAllLines("file.txt")
Dim NVP() As String = Split(line, vbTab)
Next
Debug.Print((Now.Ticks - StartTime) / 10000 & "ms")
Kinda surprising to me, but I guess the datatable has more functionality. Another new thing I discover that I'll never use :(
I need to generate a lot of random 2 character strings for my application. it's a VB console application. basically what I have tried for random strings is this:
Private Function GenerateRandomString(ByVal intLenghtOfString As Integer) As String
'Create a new StrinBuilder that would hold the random string.
Dim randomString As New StringBuilder
'Create a new instance of the class Random
Dim randomNumber As Random = New Random
'Create a variable to hold the generated charater.
Dim appendedChar As Char
'Create a loop that would iterate from 0 to the specified value of intLenghtOfString
For i As Integer = 0 To intLenghtOfString
'Generate the char and assign it to appendedChar
appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65)
'Append appendedChar to randomString
randomString.Append(appendedChar)
Next
'Convert randomString to String and return the result.
Return randomString.ToString()
End Function
AND THIS:
Private Function RandomStringGenerator(ByVal intLen As Integer) As String
Dim r As New Random()
Dim i As Integer
Dim strTemp As String = ""
For i = 0 To intLen
strTemp = strTemp & Chr(Int((26 * r.NextDouble()) + 65))
Next
Return r.Next
End Function
But when run, it displays something like this:
SR
SR
SR
SR
SR
SR
SR
SR
SR
SR
BR
BR
BR
BR
BR
BR
BR
KR
KR
KR
KR
and so on.
What is going on? I thought that I used to, a long time ago, be able to just do random.Next.
I've run into similar issues before with the Random object. The problem is that when you instantiate Random it's default seed value is the number of milliseconds since windows started up. And since you are generating random characters at several a millisecond you end up with the same seed number.
Instead you should create a shared random object instead of instantiating a new one on each call.
In another forum I answered a similar question and came up with this generalized function that could be used for your problem. It includes a metric that can be examined to see if there is a bias in the characters being generated.
Dim charUC As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim charLC As String = charUC.ToLower
Dim charNUM As String = "0123456789"
Dim charSPEC As String = "``!##$%^&*()-_=+[{]}\|;:',<.>/?" & ControlChars.Quote
Dim charCounts As New Dictionary(Of Char, Integer)
Dim PRNG As New Random 'note - defined at class level
Private Function GetRandChars(ByVal numChars As Integer, _
Optional ByVal includeUpperCase As Boolean = False, _
Optional ByVal includeLowerCase As Boolean = False, _
Optional ByVal includeNumbers As Boolean = False, _
Optional ByVal includeSpecial As Boolean = False) As String
If numChars <= 0 Then Throw New ArgumentException 'must specify valid character count
Dim includeSel As New System.Text.StringBuilder 'contains set of characters
If includeUpperCase Then includeSel.Append(charUC) 'UC to set
If includeLowerCase Then includeSel.Append(charLC) 'LC to set
If includeNumbers Then includeSel.Append(charNUM) 'numbers to set
If includeSpecial Then includeSel.Append(charSPEC) 'specials to set
If includeSel.Length = 0 Then Throw New ArgumentException 'must tell function at least one include
Dim rv As New System.Text.StringBuilder 'return value
'generate specified number of characters
For ct As Integer = 1 To numChars
Dim chSel As Char = includeSel(PRNG.Next(includeSel.Length)) 'select random character
rv.Append(chSel)
'do counts
If charCounts.ContainsKey(chSel) Then
charCounts(chSel) += 1
Else
charCounts.Add(chSel, 1)
End If
Next
Return rv.ToString 'return the random string
End Function