I have the following url
http://example.com/pa/TaskDetails.aspx?Proj=A5AF5C0D-648A-4892-A995-CDA8013F2643&Assn=2A992D9C-C511-E611-80E4-005056A13B51
I need to extract the A5AF5C0D-648A-4892-A995-CDA8013F2643 portion of the url parameter:
Proj=A5AF5C0D-648A-4892-A995-CDA8013F2643
This can be in the middle or at the end of the url. I cannot guarantee the position of it. But i always starts with Proj= and end with &. The string between this is what i want. How can i grab this within C#?
It seems that you are trying to retrieve the IDFA from a url address. I think you can easily do that by applying regular expressions to the url string.
For example, the following:
[0-9a-fA-F]{8}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][[0-9a-fA-F]{12}
Picks up every valid IDFA when applied to the URL string. You can add conditions for the head and tail of the IDFA to retrieve exactly what you are looking for:
Proj=[0-9a-fA-F]{8}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][0-9a-fA-F]{4}[-][[0-9a-fA-F]{12}&
You can test the above Regex (regular expression) syntax on one of the many free online Regex applets (e.g. https://regex101.com/)
To apply Regex to your code, please see the following thread:
c# regex matches example
You may need to create a Uri and pass the value of its Query property to the HttpUtility.ParseQueryString method:
string value = HttpUtility.ParseQueryString(new Uri("http://example.com/pa/TaskDetails.aspx?Proj=A5AF5C0D-648A-4892-A995-CDA8013F2643&Assn=2A992D9C-C511-E611-80E4-005056A13B51").Query)["Proj"];
The method is defined in System.Web.dll by the way so you need to add a reference to this one.
string som = "http://example.com/pa/TaskDetails.aspx?Proj=A5AF5C0D-648A-4892-A995-CDA8013F2643&Assn=2A992D9C-C511-E611-80E4-005056A13B51";
int startPos = som.LastIndexOf("Proj=") + "Proj=".Length + 1;
int length = som.IndexOf("&") - startPos;
string sub = som.Substring(startPos, length); //<- This will return your key
This should do it.
One solution:
string param = HttpUtility
.ParseQueryString("http://example.com/pa/TaskDetails.aspx?Proj=A5AF5C0D-648A-4892-A995-CDA8013F2643&Assn=2A992D9C-C511-E611-80E4-005056A13B51")
.Get("Proj");
Related
I want to set redirection from
www.somesite.com/products/dynamicstring/randomtext1/randomtext2
to www.somesite.com/products/dynamicstring
Is it possible to do that through Regex ?
It means if my incming url is
www.somesite.com/products/myproducts/test1/test2 it should redirect to www.somesite.com/products/myproducts/
just briefing more about this :
#TomLord i am using HttpContext.Current.Response.RedirectPermanent(matchingDefinition.To) i have all the redirects "From" and "To" in a class object, in the form of REGEX expressions.Example in From "/product/*" and To "/products" , i am reading these object and trying to redirect them, but i am not able to redirect something like /products/dynamicstring/randomtext1/ to /products/dynamicstring where dynamic string is random string , i dont find any regular expression which can be use to do this. For example /products/samples/randomtext1 should redirect to /products/samples/
Redirection cannot be done with regex alone. Google a bit what is a regular expression in reality. The short answer is: it's string-like expression that describes search pattern. So it can't redirect, not even replace a substring with substring or do anything else then match and capture parts of the matched string.
That being said, regex can help us do what you wanna. I am gonna assume you can use Javascript, cause I can't put a solution in every language. I am also gonna assume you will try to go over the code not copy paste and press enter. If you only need that hire a programmer. If you use another language, principle should be the same:
obtain URL
define regex
use capture group to extract the part of your URL that you need
construct a new URL
redirect to it
While matching the URLs in general is a fair bit more complex, like:
^(?:https?://)?(?:[\w]+\.)(?:\.?[\w]{2,})+$
As long as you are sure you will only be getting URLs and in the format you wanna, we will do it far simpler.
Basically, let's say you have:
some text with 2 dots that ends in com
then a /products/dynamicstring/
then text
then /
then text
As a regex that is:
/\w*.\w*.com\/products\/dynamicstring\/\w*\/\w*/g
Curde matching is done, but we still need to add a capture group we will use to extract part of the string we need:
/(\w*.\w*.com\/products\/)dynamicstring\/\w*\/\w*/g
Oke, now let's leverage this regex to do rest of the work:
Define regex:
var regex = /\w*.\w*.com\/products\/dynamicstring\/\w*\/\w*/g;
Get current URL. If you already have URL use it.
var currUrl = window.location.href;
Extract capture group from string:
var match = regex.exec(currUrl);
Use that to get a new URL from old one:
var redirectUrl = match[1] + myproducts/
Finally, we redirect with:
window.location.replace(redirectUrl);
I wrote all this straight from my head so I recommend you go over each step, look how it works, read some documentation about functions used. You might find an error as well as learn a lot.
I will have always an string like this:
"/FirstWord/ImportantWord/ThirdWord"
How can I extract the ImportantWord? Words can contain at most one space and they are separated by forward slashlike I put above, for example:
"/Folder/Second Folder/Content"
"/Main folder/Important/Other Content"
I always want to get the second word(Second Folder and Important considering above examples)
how about this:
string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word
I hope you need not to use the String.Split option either with specific characters or with some regular expressions. Since the inputs are well qualified paths to a directory you can use Directory.GetParent method of the System.IO.Directory class, which will give you the parent Directory as DirectoryInfo. From that you can take the Name of Directory which will be the required text.
You can use like this :
string pathFirst = "/Folder/Second Folder/Content";
string pathSecond = "/Main folder/Important/Other Content";
string reqWord1 = Directory.GetParent(pathFirst ).Name; // will give you Second Folder
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important
Additional note: The method Directory.GetParent can be nested if you need to get a name in another level.
Also you may try this:
var stringValue = "/FirstWord/ImportantWord/ThirdWord";
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord
There are several ways to solve this. The simplest one is using String.split
Char delimiter = '/';
String[] substrings = value.Split(delimiter);
String secondWord = substrings[1];
(you may want to do some input check to make sure the input is in the right format or else you will get some exception)
Other way is using regex when the pattern is simple /
If you are sure this is a path you can use other answer mention here
I have a url:
http://www.abc.com?refurl=/english/info/test.aspx?form=1&h=test&s=AB
If I use
Request.QueryString["refurl"
but gives me
/english/info/test.aspx?form=1
instead I need full url
/english/info/test.aspx?form=1&h=test&s=AB
Fix the problem, and the problem is that you place a full url as parameter refurl with out encoding it.
So where you create that url string use the UrlEncode() function, eg:
"http://www.abc.com?refurl=" + Server.UrlEncode(ReturnUrlParam)
where
ReturnUrlParam="/english/info/test.aspx?form=1&h=test&s=AB";
For that particular case you shouldn't use QueryString, (since your query string contains three parameters,) instead use Uri class, and Uri.Query will give you the required result.
Uri uri = new Uri(#"http://www.abc.com?refurl=/english/info/test.aspx?form=1&h=test&s=AB");
string query = uri.Query;
Which will give you :
?refurl=/english/info/test.aspx?form=1&h=test&s=AB
Later you can remove ?refurl= to get the desired output.
I am pretty sure there is no direct way in the framework for your particular requirement, you have to implement that in your code and that too with string operations.
I had similar situation some time ago.
I solved it by encoding refurl value.
now my url looks similar to that one:
http://www.abc.com?refurl=adsf45a4sdf8sf18as4f6as4fd
I have created 2 methods:
public string encode(string);
public string decode(string);
Before redirect or where you have your link, you simple encode the link and where you are reading it, decode before use:
Response.redirect(String.Format("http://www.abc.com?refurl={0}", encode(/english/info/test.aspx?form=1&h=test&s=AB));
And in the page that you are using refurl:
$refUrl = Request.QueryString["refurl"];
$refUrl = decode($refUrl);
EDIT:
encode/decode methods I actually have as extension methods, then for every string I can simply use string.encode() or string.decode().
you should replace the & with &.
I am currently passing a parameter to a SQL string like this -
grid=0&
And I am using a RegEx to get the 0 value like so-
Match match = Regex.Match(input, #"grid=([A-Za-z0-9\-]+)\&$",
RegexOptions.IgnoreCase);
string grid = match.Groups[1].Value;
which works perfectly.
However as development has progressed it is clear that more parameters will be added to the string like so-
grid=0&hr=3&tb=0
These parameters may come in a different order in the string each time so clearly the RegEx I am currently using wont work. I have looked into it and think Split may be an option however not sure.
What would the best method be and how could I apply it to my current problem?
If you're parsing query string and looking for an alternative to Regex, there is a specialized class and method for that, it returns collection of parameters:
string s = "http://www.something.com?grid=0&hr=3&tb=0";
Uri uri = new Uri(s);
var result = HttpUtility.ParseQueryString(uri.Query);
You have to include System.Web namespace.
You can access each of the parameters' values by using it's key:
foreach (string key in result.Keys)
{
string value = result[key];
// action...
}
Regexes can still be used here. Consider adding another capture group to capture the property name, and then looping over all of the results using Matches rather that Match, or calling Match multiple times.
I am consuming the Twitter API and want to convert all URLs to hyperlinks.
What is the most effective way you've come up with to do this?
from
string myString = "This is my tweet check it out http://tinyurl.com/blah";
to
This is my tweet check it out http://tinyurl.com/>blah
Regular expressions are probably your friend for this kind of task:
Regex r = new Regex(#"(https?://[^\s]+)");
myString = r.Replace(myString, "$1");
The regular expression for matching URLs might need a bit of work.
I did this exact same thing with jquery consuming the JSON API here is the linkify function:
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
This is actually an ugly problem. URLs can contain (and end with) punctuation, so it can be difficult to determine where a URL actually ends, when it's embedded in normal text. For example:
http://example.com/.
is a valid URL, but it could just as easily be the end of a sentence:
I buy all my witty T-shirts from http://example.com/.
You can't simply parse until a space is found, because then you'll keep the period as part of the URL. You also can't simply parse until a period or a space is found, because periods are extremely common in URLs.
Yes, regex is your friend here, but constructing the appropriate regex is the hard part.
Check out this as well: Expanding URLs with Regex in .NET.
You can add some more control on this by using MatchEvaluator delegate function with regular expression:
suppose i have this string:
find more on http://www.stackoverflow.com
now try this code
private void ModifyString()
{
string input = "find more on http://www.authorcode.com ";
Regex regx = new Regex(#"\b((http|https|ftp|mailto)://)?(www.)+[\w-]+(/[\w- ./?%&=]*)?");
string result = regx.Replace(input, new MatchEvaluator(ReplaceURl));
}
static string ReplaceURl(Match m)
{
string x = m.ToString();
x = "< a href=\"" + x + "\">" + x + "</a>";
return x;
}
/cheer for RedWolves
from: this.replace(/[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/, function(m){...
see: /[A-Za-z]+://[A-Za-z0-9-]+.[A-Za-z0-9-:%&\?/.=]+/
There's the code for the addresses "anyprotocol"://"anysubdomain/domain"."anydomainextension and address",
and it's a perfect example for other uses of string manipulation. you can slice and dice at will with .replace and insert proper "a href"s where needed.
I used jQuery to change the attributes of these links to "target=_blank" easily in my content-loading logic even though the .link method doesn't let you customize them.
I personally love tacking on a custom method to the string object for on the fly string-filtering (the String.prototype.linkify declaration), but I'm not sure how that would play out in a large-scale environment where you'd have to organize 10+ custom linkify-like functions. I think you'd definitely have to do something else with your code structure at that point.
Maybe a vet will stumble along here and enlighten us.