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]
Related
I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();
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;
}
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/")
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();