Trim url to last subfolder in VB - vb.net

I have a string in VB:
url = "http://example.com/aa/bb/cc.html"
I want to trim this url to the last sub-folder so it becomes:
url = "http://example.com/aa/bb"
I need everything after the last "/" to be removed.
I am thinking of using the string.lastindexof("/") method but don't know how to continue from there.

use a combination of Substring and Lastindex of. Like this:
url.substring(0,url.lastindexof("/"))
might be that you need to substract 1 from the lastindexof("/") value, i always forget it^^

When working with an URL, consider using the Uri class. Then handling such cases become easy.
Create a Uri instance:
Dim url = new Uri("http://example.com/aa/bb/cc.html")
Then you can either do
Dim result = url.AbsoluteUri.Remove(url.AbsoluteUri.Length - url.Segments.Last().Length)
or something like
Dim result = new Uri(url, ".").AbsoluteUri

You could use String.Remove() to remove the unwanted part of the string:
Dim temp As String = "http://example.com/aa/bb/cc.html"
Dim index As String = temp.LastIndexOf("/"c)
Dim ret As String = temp.Remove(index, temp.Length - index)

Related

Vb.net, replace any number at the end of a string with a placeholder

I have many strings that have numbers at the end. The numbers can be of any size, for example:
myvar123
mysecondvar3
mythirdvar219107
The strings can have numbers even inside the name, not only at the end.
for example:
my2varable123
some123variable9480395
I would need to replace any number at the END with a placeholder. (NOT those inside the varname.)
for example:
my2varable123 should become: my2variable%placeholder%
some123variable9480395 should become: some123variable%placeholder%
The only way that comes to my mind is to go through the string using .right() and remove the char if it is numeric until I find the first non numeric char. Then in the end append the placeholder, but it looks like a lot of work for a rather simply problem.
Is there a better way to do this?
You could use a Regex for this.
Dim str As String = "some123variable9480395"
Dim pattern As String = "\d+$"
Dim replacement As String = "%placeholder%"
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement)

Split String by last occurence

I have a String like this:
www.myserver.net/Files/Pictures/2014/MyImage.jpg
And I want to split it, so I get the Substring after the last occurence of /.
Which means I like to get MyImage.jpg
I tried it like this:
MsgBox(URL.Substring(URL.LastIndexOf("/"), URL.Length - 1))
But that wont work. Can someone help me out how to do this in VB.Net?
C# is also okay, after I've understood the logic, I can convert it myself.
Use System.IO.Path.GetFileName instead:
Dim path = "www.myserver.net/Files/Pictures/2014/MyImage.jpg"
Dim filename = System.IO.Path.GetFileName(path) ' MyImage.jpg
For the sake of completeness, you could also use String.Split or String.Substring:
filename = path.Split("/"c).Last()
' or
Dim lastIndex = path.LastIndexOf("/")
If lastIndex >= 0 Then
fileName = path.Substring(lastIndex + 1)
End If
But it is more error-prone and less readable.

How to split in VB.NET

I am using VB.NET code.
I have got the below string.
http://localhost:3282/ISS/Training/SearchTrainerData.aspx
Now I want to split the above string with "/" as well. I want to store the value SearchTrainerData.aspx in a variable.
In my case
Dim str as String
str = "SearchTrainerData.aspx"
What would be the code which will split the above string and further store it in a variable?
Try to use the function String.Split.
Your "string" is obviously a URL which means you should use the System.Uri class.
Dim url As Uri = New Uri("http://localhost:3282/ISS/Training/SearchTrainerData.aspx")
Dim segments As String() = url.Segments
Dim str As String = segments(segments.Length - 1)
This will also allow you to get all kinds of other interesting information about your "string" without resorting to manual (and error-prone) parsing.
The Split function takes characters, which VB.NET represents by appending a 'c' to the end of a one-character string:
Dim sentence = "http://localhost:3282/ISS/Training/SearchTrainerData.aspx"
Dim words = sentence.Split("/"c)
Dim lastWord = words(words.length - 1)
I guess what you are actually looking for is the System.Uri Class. Which makes all string splitting that you are looking for obsolete.
MSDN Documentation for System.Uri
Uri url = new Uri ("http://...");
String[] parts = url.Segments;
Use split(). You call it on the string instance, passing in a char array of the delimiters, and it returns to you an array of strings. Grab the last element to get your "SearchTrainerData.aspx."

How can I get the URL and Querystring? vb.net

I am refactoring some legacy code. The app was not using querystrings. The previous developer was hard coding some variables that the app uses in other places.
Like this using VB.NET
so.Cpage = "ContractChange.aspx"
My question is can I programatically set this value and include the current querystring?
I want so.Cpage to be something like ContractChange.aspx?d=1&b=2
Can I do this with the request object or something? Note, I don't need the domain.
To get the current query string you would simply do something like the following:
Dim query as String = Request.QueryString("d")
This will assign the value of the "d" querystring to the string variable "query". Note that all query string values are strings, so if you're passing numbers around, you'll need to "cast" or convert those string values to numerics (be careful of exceptions when casting, though). For example:
Dim query as String = Request.QueryString("d")
Dim iquery as Integer = CType(query, Integer)
The QueryString property of the Request object is a collection of name/value key pairs. Specifically, it's of type System.Collections.Specialized.NameValueCollection, and you can iterate through each of the name/value pairs as so:
Dim coll As System.Collections.Specialized.NameValueCollection = Request.QueryString
Dim value As String
For Each key As String In coll.AllKeys
value = coll(key)
Next
Using either of these mechanisms (or something very similar) should enable you to construct a string variable which contains the full url (page and querystrings) that you wish to navigate to.
Try this:
so.Cpage = "ContractChange.aspx?" & Request.RawUrl.Split("?")(1)
In VB.Net you can do it with the following.
Dim id As String = Request.Params("RequestId")
If you want to process this in as an integer, you can do the following:
Dim id As Integer
If Integer.TryParse(Request.Params("RequestId"), id) Then
DoProcessingStuff()
End If
try this
Dim name As String = System.IO.Path.GetFileName(Request.ServerVariables("SCRIPT_NAME"))
Dim qrystring As String = Request.ServerVariables("QUERY_STRING")
Dim fullname As String = name & "/" & qrystring
Not sure about the syntax in VB.NET but in C# you would just need to do
StringId = Request.QueryString.Get("d");
Hope this helps.

String substring function

How can i get the string within a parenthesis with a custom function?
e.x. the string "GREECE (+30)" should return "+30" only
There are some different ways.
Plain string methods:
Dim left As Integer = str.IndexOf('(')
Dim right As Integer= str.IndexOf(')')
Dim content As String = str.Substring(left + 1, right - left - 1)
Regular expression:
Dim content As String = Regex.Match(str, "\((.+?)\)").Groups[1].Value
For the general problem, I'd suggest using Regex. However, if you are sure about the format of the input string (only one set of parens, open paren before close paren), this would work:
int startIndex = s.IndexOf('(') + 1;
string result = s.Substring(startIndex, s.LastIndexOf(')') - startIndex);
With regular expressions.
Dim result as String = System.Text.RegularExpressions.Regex.Match("GREECE (+30)", "\((?<Result>[^\)]*)\)").Groups["Result"].Value;
Code is not tested, but I expect only compilation issues.
You could look a regular expressions, or otherwise play with the IndexOf() function
In Python, using the string index method and slicing:
>>> s = "GREECE(+30)"
>>> s[s.index('(')+1:s.index(')')]
'+30'