I tried to take only this part(after the "j&q") from link
(http://www.google.com/aclk?sa=lai=CEvAD5thCTfHPCIq5gwe2lOWKD6n_uOIB4bzDkxm8uIhRCAAQASDrxZ0GKANQgI6s1ANgybblirSk2A-gAYem9NwDyAEBqQLN5n97JxulPqoEGk_QITE_eyPbZTKIyNFl8dQhptl05oxQ2fHjgAWQTg&sig=AGiWqtwLGY6f1Gnci0e0ojoRsLBxr9joLg&adurl=http://www.mediterraholidays.com/egypt/cairo-and-nile-cruise&rct=j&q=egpyt%20package%20trips).
I used ^.*q=.*$ but with this. I need only after the j&q part if it has.
Why don't you use System.Uri class for this:
Uri url = new Uri("http://www.google.com/aclk?sa=lai=CEvAD5thCTfHPCIq5gwe2lOWKD6n_uOIB4bzDkxm8uIhRCAAQASDrxZ0GKANQgI6s1ANgybblirSk2A-gAYem9NwDyAEBqQLN5n97JxulPqoEGk_QITE_eyPbZTKIyNFl8dQhptl05oxQ2fHjgAWQTg&sig=AGiWqtwLGY6f1Gnci0e0ojoRsLBxr9joLg&adurl=http://www.mediterraholidays.com/egypt/cairo-and-nile-cruise&rct=j&q=egpyt%20package%20trips");
var queryString = HttpUtility.ParseQueryString(url.Query);
var q = queryString["q"];
The q variable holds the value: egpyt package trips
&q=(?<data>[^&]*)
The answer needs to be at least 30 chars, so I add some joke:
“Knock, knock.”
“Who’s there?”
very long pause….
“Java.”
Related
I have a URL, which is like http://example.com/UK/Deal.aspx?id=322
My target is to remove the locale(country) part, to make it like http://example.com/Deal.aspx?id=322
Since the URL may have other similar formats like: https://ssl.example.com/JP/Deal.aspx?id=735, using "substring" function is not a good idea.
What I can think about is to use the following method for separating them, and map them back later.
HttpContext.Current.Request.Url.Scheme
HttpContext.Current.Request.Url.Host
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.Url.Query
And, suppose HttpContext.Current.Request.Url.AbsolutePath will be:
/UK/Deal.aspx?id=322
I am not sure how to deal with this since my boss asked me not to use "regular expression"(he thinks it will impact performance...)
Except "Regular Expression", is there any other way to remove UK from it?
p.s.: the UK part may be JP, DE, or other country code.
By the way, for USA, there is no country code, and the url will be http://example.com/Deal.aspx?id=322
Please also take this situation into consideration.
Thank you.
Assuming that you'll have TwoLetterCountryISOName in the Url. yYou can use UriBuilder class to remove the path from Uri without using the Regex.
E.g.
var originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
if (IsLocaleEnabled(sourceUri))
{
var builder = new UriBuilder(sourceUri);
builder.Path
= builder.Path.Replace(sourceUri.Segments[1] /* remove UK/ */, string.Empty);
// Construct the Uri with new path
Uri newUri = builder.Uri;;
}
Update:
// Cache the instance for performance benefits.
static readonly Regex regex = new Regex(#"^[aA-zZ]{2}\/$", RegexOptions.Compiled);
/// <summary>
/// Regex to check if Url segments have the 2 letter
/// ISO code as first ocurrance after root
/// </summary>
private bool IsLocaleEnabled(Uri sourceUri)
{
// Update: Compiled regex are way much faster than using non-compiled regex.
return regex.IsMatch(sourceUri.Segments[1]);
}
For performance benefits you must cache it (means keep it in static readonly field). There's no need to parse a pre-defined regex on every request. This way you'll get all the performance benefits you can get.
Result - http://example.com/Deal.aspx?id=322
It all depends on whether the country code always has the same position. If it's not, then some more details on the possible formats are required.. Maybe you could check, if the first segment has two chars or something, to be sure it really is a country code (not sure if this is reliable though). Or you start with the filename, if it's always in the format /[optionalCountryCode]/deal.aspx?...
How about these two approaches (on string level):
public string RemoveCountryCode()
{
Uri originalUri = new Uri("http://example.com/UK/Deal.aspx?id=322");
string hostAndPort = originalUri.GetLeftPart(UriPartial.Authority);
// v1: if country code is always there, always has same position and always
// has format 'XX' this is definitely the easiest and fastest
string trimmedPathAndQuery = originalUri.PathAndQuery.Substring("/XX/".Length);
// v2: if country code is always there, always has same position but might
// not have a fixed format (e.g. XXX)
trimmedPathAndQuery = string.Join("/", originalUri.PathAndQuery.Split('/').Skip(2));
// in both cases you need to join it with the authority again
return string.Format("{0}/{1}", hostAndPort, trimmedPathAndQuery);
}
If the AbsolutePath will always have the format /XX/...pagename.aspx?id=### where XX is the two letter country code, then you can just strip off the first 3 characters.
Example that removes the first 3 characters:
var targetURL = HttpContext.Current.Request.Url.AbsolutePath.Substring(3);
If the country code could be different lengths, then you could find the index of the second / character and start the substring from there.
var sourceURL = HttpContext.Current.Request.Url.AbsolutePath;
var firstOccurance = sourceURL.IndexOf('/')
var secondOccurance = sourceURL.IndexOf('/', firstOccurance);
var targetURL = sourceURL.Substring(secondOccurance);
The easy way would be to treat as string, split it by the "/" separator, remove the fourth element, and then join them back with the "/" separator again:
string myURL = "https://ssl.example.com/JP/Deal.aspx?id=735";
List<string> myURLsplit = myURL.Split('/').ToList().RemoveAt(3);
myURL = string.Join("/", myURLsplit);
RESULT: https://ssl.example.com/Deal.aspx?id=735
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/")
Help me to parse this message:
text=&direction=re&orfo=rus&files_id=&message=48l16qL2&old_charset=utf-8&template_id=&HTMLMessage=1&draft_msg=&re_msg=&fwd_msg=&RealName=0&To=john+%3Cjohn11%40gmail.com%3E&CC=&BCC=&Subject=TestSubject&Body=%3Cp%3EHello+%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82+%D1%82%D0%B5%D0%BA%D1%81%D1%82%3Cbr%3E%3Cbr%3E%3C%2Fp%3E&secur
I would like to get information in an KeyValuePair:
Key - Value
text -
direction - re
and so on.
And how to convert this: Hello+%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82+%D1%82%D0%B5%D0%BA%D1%81%...
there are cyrillic character.
Thanks.
If you want to use a Regex, you can do it like this:
// I only added the first 3 keys, but the others are basically the same
Regex r = new Regex(#"text=(?<text>.*)&direction=(?<direction>.*)&orfo=(?<orfo>.*)");
Match m = r.Match(inputText);
if(m.Success)
{
var text = m.Groups["text"].Value; // result is ""
var direction = m.Groups["direction"].Value; // re
var orfo = m.Groups["orfo"].Value;
}
However, the method suggested by BoltClock is much better:
System.Collections.Specialized.NameValueCollection collection =
System.Web.HttpUtility.ParseQueryString(inputString);
It looks like you are dealing with a URI, better to use the proper class than try and figure out the detailed processing.
http://msdn.microsoft.com/en-us/library/system.uri.aspx
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 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.