Extracting Portion of Url using VB.net - vb.net

I have this URL
https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607
I am trying to Extract 31.888433,73.263572 from the URL
and send 31.888433 to TextBox 1
and 73.263572 to TextBox 2
Can you give me an example how can i do this with regex or anything else

You can use string.split(). This method takes an array of chars which are the discriminants for the splitting. The better solution is to split by '/', take the string that starts with '#' and then split it by ','. You'll have an array with two string: first latitude, second longitude.
Should be immediate using LINQ

The explanation is in the code comments.
Dim strURL As String = "https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
'Find the index of the first occurance of the # character
Dim index As Integer = strURL.IndexOf("#")
'Get the string from that the next character to the end of the string
Dim firstSubstring As String = strURL.Substring(index + 1)
'Get a Char array of the separators
Dim separators As Char() = {CChar(",")}
'Split the string into an array based on the separator; the separator is not part of the array
Dim strArray As String() = firstSubstring.Split(separators)
'The first and second elements of the array is what you want
Dim strTextBox1 As String = strArray(0)
Dim strTextBox2 As String = strArray(1)
Debug.Print($"{strTextBox1} For TextBox1 and {strTextBox2} for TextBox2")

Finally Made a working Code Myself
Private _reg As Regex = New
Regex("#(-?[\d].[\d]),(-?[\d].[\d])", RegexOptions.IgnoreCase)
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
Dim url As String = WebBrowser2.Url.AbsoluteUri.ToString()
' The input string.
Dim value As String = WebBrowser2.Url.ToString
Dim myString As String = WebBrowser2.Url.ToString
Dim regex1 = New Regex("#(-?\d+\.\d+)")
Dim regex2 = New Regex(",(-?\d+\.\d+)")
Dim match = regex1.Match(myString)
Dim match2 = regex2.Match(myString)
If match.Success Then
Dim match3 As String = match.Value.Replace("#", "")
Dim match4 As String = match2.Value.Replace(",", "")
Label1.Text = match3
Label2.Text = match4
End If
End Sub

Dim url As String = "www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
Dim temp As String = Regex.Match(url, "#.*,").Value.Replace("#", "")
Dim arrTemp As String() = temp.Split(New String() {","}, StringSplitOptions.None)
Label1.Text = arrTemp(0)
Label2.Text = arrTemp(1)

Related

String Manipulation from "[1_5],[1_3],[1_5]" to "5,3,5"

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

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

Split a string in VB.NET

I am trying to split the following into two strings.
"SERVER1.DOMAIN.COM Running"
For this I use the code.
Dim Str As String = "SERVER1.DOMAIN.COM Running"
Dim strarr() As String
strarr = Str.Split(" ")
For Each s As String In strarr
MsgBox(s)
Next
This works fine, and I get two message boxes with "SERVER1.DOMAIN.COM" and "Running".
The issue that I am having is that some of my initial strings have more than one space.
"SERVER1.DOMAIN.COM Off"
There are about eight spaces in-between ".COM" and "Off".
How can I separate this string in the same way?
Try this
Dim array As String() = strtemp.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Use this way:
Dim line As String = "SERVER1.DOMAIN.COM Running"
Dim separators() As String = {"Domain:", "Mode:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
Here's a method using Regex class:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each s In str
Dim regx = New Regex(" +")
Dim splitString = regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next
And the LINQ way to do it:
Dim str() = {"SERVER1.DOMAIN.COM Running", "mydomainabc.es not-running"}
For Each splitString In From s In str Let regx = New Regex(" +") Select regx.Split(s)
Console.WriteLine("Part 1:{0} | Part 2:{1}", splitString(0), splitString(1))
Next

How to select a value from a comma delimited string?

I have a string that contains comma delimited text. The comma delimited text comes from an excel .csv file so there are hundreds of rows of data that are seven columns wide. An example of a row from this file is:
2012-10-01,759.05,765,756.21,761.78,3168000,761.78
I want to search through the hundreds of rows by the date in the first column. Once I find the correct row I want to extract the number in the first position of the comma delimited string so in this case I want to extract the number 759.05 and assign it to variable "Open".
My code so far is:
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
Dim Year As String = 2012
Dim Quarter As String = Q4
If Quarter = "Q4" Then
Dim Open As Integer =
End If
Once I can narrow it down to the right row I think something like row.Split(",")(1).Trim) might work.
I've done quite a bit of research but I can't solve this on my own. Any suggestions!?!
ADDITIONAL INFORMATION:
Private Function RequestWebData(ByVal pstrURL As String) As String
Dim objWReq As WebRequest
Dim objWResp As WebResponse
Dim strBuffer As String
'Contact the website
objWReq = HttpWebRequest.Create(pstrURL)
objWResp = objWReq.GetResponse()
'Read the answer from the Web site and store it into a stream
Dim objSR As StreamReader
objSR = New StreamReader(objWResp.GetResponseStream)
strBuffer = objSR.ReadToEnd
objSR.Close()
objWResp.Close()
Return strBuffer
End Function
MORE ADDITIONAL INFORMATION:
A more complete picture of my code
Dim tickerArray() As String = {"GOOG", "V", "AAPL", "BBBY", "AMZN"}
For Each tickerValue In Form1.tickerArray
Dim strURL As String
Dim strBuffer As String
'Creates the request URL for Yahoo
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
'Create Array
Dim lines As Array = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
'Add Rows to DataTable
dr = dt.NewRow()
dr("Ticker") = tickerValue
For Each columnQuarter As DataColumn In dt.Columns
Dim s As String = columnQuarter.ColumnName
If s.Contains("-") Then
Dim words As String() = s.Split("-")
Dim Year As String = words(0)
Dim Quarter As String = words(1)
Dim MyValue As String
Dim Open As Integer
If Quarter = "Q1" Then MyValue = Year & "-01-01"
If Quarter = "Q2" Then MyValue = Year & "-04-01"
If Quarter = "Q3" Then MyValue = Year & "-07-01"
If Quarter = "Q4" Then MyValue = Year & "-10-01"
For Each line In lines
Debug.WriteLine(line)
If line.Split(",")(0).Trim = MyValue Then Open = line.Split(",")(1).Trim
dr(columnQuarter) = Open
Next
End If
Next
dt.Rows.Add(dr)
Next
Right now in the For Each line in lines loop, Debug.WriteLine(line) outputs 2,131 lines:
From
Date,Open,High,Low,Close,Volume,Adj Close
2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74
2013-02-04,767.69,770.47,758.27,759.02,3040500,759.02
2013-02-01,758.20,776.60,758.10,775.60,3746100,775.60
All the way to...
2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
But, what I expect is for Debug.WriteLine(line) to output one line at a time in the For Each line in lines loop. So I would expect the first output to be Date,Open,High,Low,Close,Volume,Adj Close and the next output to be 2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74. I expect this to happen 2,131 times until the last output is 2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
You could loop through the lines and call String.Split to parse the columns in each line, for instance:
Dim lines() As String = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Next
However, sometimes CSV isn't that simple. For instance, a cell in a spreadsheet could contain a comma character, in which case it would be represented in CSV like this:
example cell 1,"example, with comma",example cell 3
To make sure you're properly handling all possibilities, I'd recommend using the TextFieldParser class. For instance:
Using parser As New TextFieldParser(New StringReader(strBuffer))
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",")
While Not parser.EndOfData
Try
Dim columns As String() = parser.ReadFields()
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Catch ex As MalformedLineException
' Handle the invalid formatting error
End Try
End While
End Using
I would break it up into a List(of string()) - Each row being a new entry in the list.
Then loop through the list and look at Value(0).
If Value(0) = MyValue, then Open = Value(1)
You can use String.Split and this linq query:
Dim Year As Int32 = 2012
Dim Month As Int32 = 10
Dim searchMonth = New Date(Year, Month, 1)
Dim lines = strBuffer.Split({Environment.NewLine}, StringSplitOptions.None)
Dim dt As Date
Dim open As Double
Dim opens = From line In lines
Let tokens = line.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Where Date.TryParse(tokens(0), dt) AndAlso dt.Date = searchMonth AndAlso Double.TryParse(tokens(1), open)
If opens.Any() Then
open = Double.Parse(opens.First().tokens(1))
End If

retrieve unique values from string of numbers

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()