I got a very long string that cointains querystrings and and some regular site urls in it. it looks something like
http://www.mysite.com/site/site?pageId=1234&otherId=4321
I would like to get just the http://www.mysite.com from this string. Im thinking maybe a regular expression could do the trick, but Im def not quilfied to write any of that :) so could i get some help?
EDIT
i need a solution so i can pass url string and get the base url from that. Not my current Url
thanks guys, appreciate it as always.
Please try this:
string uri = Request.Url.GetLeftPart(UriPartial.Authority);
You can check with this also:
var url = new Uri("http://www.mysite.com/site/site?pageId=1234&otherId=4321");
string uri = url.GetLeftPart(UriPartial.Authority);
Solution
var url = new Uri("http://www.mydomain.com/Site/Subsite?page=site");
var baseUrl = url.Host;
As the author asked for a regular expression, that's it:
static string ExtractBaseUrl(string url)
{
Regex regex = new Regex(#"^https?:\/\/[^\/]+");
Match resultm = regex.Match(url);
if (resultm.Success)
return resultm.Groups[0].Value;
else return null;
}
Related
this is my Set of string inside richtextbox1..
/Category/5
/Category/4
/Category/19
/Category/22
/Category/26
/Category/27
/Category/24
/Category/3
/Category/1
/Category/15
http://example.org/Category/15/noneedtoadd
i want to change all the starting "/" with some url like "http://example.com/"
output:
http://example.com/Category/5
http://example.com/Category/4
http://example.com/Category/19
http://example.com/Category/22
http://example.com/Category/26
http://example.com/Category/27
http://example.com/Category/24
http://example.com/Category/3
http://example.com/Category/1
http://example.com/Category/15
http://example.org/Category/15/noneedtoadd
just asking, what is the pattern for that? :)
You don't need a regular expression here. Iterate through the items in your list and use String.Format to build the desired URL.
String.Format(#"http://example.com{0}", str);
If you want to check to see whether one of the items in that textbox is a fully-formed URL before prepending the string, then use String.StartsWith (doc).
if (!String.StartsWith("http://")) {
// use String.Format
}
Since you're dealing with URIs, you can take advantage of the Uri Class which can resolve relative URIs:
Uri baseUri = new Uri("http://example.com/");
Uri result1 = new Uri(baseUri, "/Category/5");
// result1 == {http://example.com/Category/5}
Uri result2 = new Uri(baseUri, "http://example.org/Category/15/noneedtoadd");
// result2 == {http://example.org/Category/15/noneedtoadd}
The raw regex pattern is ^/ which means that it will match a slash at the beginning of the line.
Regex.Replace (text, #"^/", "http://example.com/")
how can i trim a youtube url so it only returns the video id for example http://www.youtube.com/watch?v=VPqTW-9U9nU. how would i return VPqTW-9U9nU. this has to be for several url inputted. I would like to use regex but I do not understand it at all. so if somebody has a solution with regex could you explain it in abit more details :)
Without doing any string manipulation you can use Uri and ParseQueryString
Uri uri = new Uri("http://www.youtube.com/watch?v=VPqTW-9U9nU");
var s = HttpUtility.ParseQueryString(uri.Query).Get("v");
No RegEx needed in this case:
string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string videoId = url.Substring(url.IndexOf("?v=") + 3);
Why not just stick with something simple?
string youTubeUrl = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string id = youTubeUrl.Replace("http://www.youtube.com/watch?v=", String.Empty);
Regular expressions are handy, but sometimes overkill and can make your code harder to understand when you use them in places you don't need them.
Try something like this:
string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string video_id = url.Substring(0,url.LastIndexOf("=')+1);
The other answers look right, too.
You could also use String.Split():
url.Split(new[] { '=' }, 2)[1]
This seems like a really easy one but everything I try doesn't seem to work
say I have the following string:
string myString = "http://www.mysite.com/folder/file.jpg";
How can I process that to remove the URL and just leave "file.jpg" as the string value?
Thanks!
Kris
You can always use System.IO.Path methods
string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg
If you do want to process more complex URIs you can pass it thought the System.Uri type and grab the AbsolutePath
string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);
string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);
This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 4 years ago.
I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param
Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.
I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.
I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.
Use this:
string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
This code by Tejs isn't the 'proper' way to get the query string from the URI:
string.Join(string.Empty, uri.Split('?').Skip(1));
You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
MSDN
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
I had to do this for a modern windows app. I used the following:
public static class UriExtensions
{
private static readonly Regex _regex = new Regex(#"[?&](\w[\w.]*)=([^?&]+)");
public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
{
var match = _regex.Match(uri.PathAndQuery);
var paramaters = new Dictionary<string, string>();
while (match.Success)
{
paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
match = match.NextMatch();
}
return paramaters;
}
}
Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.
The other option is to use string.Split().
string url = #"http://example.com/file?a=1&b=2&c=string%20param";
string[] parts = url.Split(new char[] {'?','&'});
///parts[0] now contains http://example.com/file
///parts[1] = "a=1"
///parts[2] = "b=2"
///parts[3] = "c=string%20param"
For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:
var arguments = uri.Query
.Substring(1) // Remove '?'
.Split('&')
.Select(q => q.Split('='))
.ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());
Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.
In a single line of code:
string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));
Microsoft Azure offers a framework that makes it easy to perform this.
http://azure.github.io/azure-mobile-services/iOS/v2/Classes/MSTable.html#//api/name/readWithQueryString:completion:
You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.
i just want to get a text from textbox that is betwen two dots for example. www. abc.org . h
in C#
string url = "www.google.com";
string[] split_strings = url.Split('.');
Console.WriteLine(split_strings[1]);
Get String From Textbox:
string url = textbox_url.Text;
string[] split_strings = url.Split('.');
Console.WriteLine(split_strings[1]);
But please, use try and catch ;)
You'll need to be a bit more specific with your question I think. Now, if you're just looking to extract the middle part of the address, something like the following should do the job:
var parts = textbox.Text.Split(new char[] {'.'});
if (parts.Length < 3) throw new InvalidOperationException("Invalid address.");
var middlePart = parts[1];
Is that as specific as your requirement is?
does it only have to work for www.SOMESITE.com
what about other tld extensions like, .net, .org, .co.uk, .ie etc...
what about other subdomains like, www2., api., news. etc...
what about domains with no subdomain like, google.com, theregister.co.uk, bit.ly
if that's a simple as your requirement is,
then
textBox.Text.Replace("www.", "").Replace(".com", "");
though I've a feeling you haven't thought through or fully explained your requirements.
If it is a more complex scenario, you might want to look at Regular expressions.
string haystack= "www.google.com";
string needle = "google";
string myWord = GetWordFromString(haystack, needle);
private string GetWordFromString(string haystack, string needle)
{
if (haystack.ToLower().Contains(needle))
{
return needle;
}
}
I re-read the post with comments I can see that you probably don't know what word you are going to extract... I think the first answer is the one that you are looking fore.
There's also regular expressions for extracting the domainname out of a url if that is your specific need.
Something like this:
public static string ExtractDomainName(string Url)
{
return System.Text.RegularExpressions.Regex.Replace(
Url,
#"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$",
"$2"
);
}
string text = "www. abc.org . h";
int left = Math.Max(text.IndexOf('.'), 0),
right = Math.Min(text.LastIndexOf('.'), text.Length - 1);
string result = text.Substring(left+1, right - left-1).Trim();