I am using one web application where i am taking current url which contains culture code.
There are two url patterns where i have to validate culture code.
First pattern:
var url = "http://localhost:1469/en-US";
Second pattern:
var url = "http://localhost:1469/somepagename/en-US";
Please suggest me some regex that will validate url contains culture code or not.
Just to answer your question, you can try something like this:
string pat = #"[a-z]{2}-[A-Z]{2}";
Regex regex = new Regex(pat);
var url1 = "http://localhost:1469/en-US";
var url2 = "http://localhost:1469/somepagename/en-US";
Console.WriteLine(regex.Matches(url1)[0]);
Console.WriteLine(regex.Matches(url2)[0]);
Related
I have a textbox where users can paste a URL address. I want to add a directory name to the URL before saving it in the database.
<asp:TextBox ID="urlTextbox" runat="server"></asp:TextBox>
Code behind
TextBox url = urlTextbox as TextBox;
string urlString = urlTextbox.Text;
Let's say the urlString = "mydomain.com/123456". I want to replace it with "mydomain.com/directory/123456". mydomain.com/directory is the same for all the URLs. The last part "123456" changes only.
Thank you
I'd suggest seeing if your needs are met with the UriBuilder class.
UriBuilder url = new UriBuilder(urlTextbox.Text);
Now you can use the various properties to change your url.
string formattedUrl = string.Format("{0}://{1}/directory/{2}", url.Scheme, url.Host, url.Path);
A better idea is to adjust the URL with another / same UriBuilder as noted by Jared.
UriBuilder url = new UriBuilder(urlTextbox.Text);
url.Path = string.Format("directory/{0}", url.Path);
Use this object as a Uri by simply doing this
Uri formattedUrl = url.Uri;
Or convert to a string if needed.
string formattedUrl = url.ToString();
You can also use Uri.TryParse(...) to verify if it's a valid URL being entered into the text box.
To get the individual query parameters, you can look at the Uri object.
UriBuilder url = new UriBuilder("mydomain.com/123456?qs=aaa&bg=bbb&pg=ccc");
url.Path = string.Format("directory/{0}", url.Path);
Uri formattedUrl = url.Uri;
string queryString = formattedUrl.Query;
// parse the query into a dictionary
var parameters = HttpUtility.ParseQueryString(queryString);
// get your parameters
string qs = parameters.Get("qs");
string bg = parameters.Get("bg");
string pg = parameters.Get("pg");
You can use string functions Split and Join to achieve your result. An example code is shown below
List<string> parts = urlString.Split(new char[] { '/'}).ToList();
parts.Insert(parts.Count - 1, "directory");
urlString = string.Join("/", parts);
This is one way of doing. Split the urlString using .split() function.
string[] parts = urlString.Split('/');
parts[parts.Length-1] will have that number. Append it to the string you want.
I'd do something like this:
//Assuming the address in urlString has the format mydomain.com/123456
string[] urlParts = urlString.Split('/');
string directory = "directory";
string finalUrl = urlParts[0] + "/" + directory + "/" + urlParts[1];
Be careful if the address has other "/" characters, like if preceded by http:// or something like that.
Hope it helps.
Simply use concatenation:
save in a temporary string
temp="mydomain.com/directory/"
and save the changing part in another string like
temp2="123456"
now concatenate both temp1 and temp2 like below.
urlString=temp1+temp2;
My page URL is mentioned below, I want to get JID value.
http://.........../abc.aspx?JID=00001833
I can get complete URL from this code, but I want to get specific value.
string url = driver.Url;
Console.WriteLine(url);
UPDATE:
As JeffC suggested the proper way to get parameters you should use HttpUtility.ParseQueryString
String yoururl = "http://example.com/abc.aspx?JID=00001833";
Uri theUri = new Uri(yoururl);
String jid = HttpUtility.ParseQueryString(theUri.Query).Get("JID");
Console.WriteLine(jid);
Read more about ParseQueryString here: https://msdn.microsoft.com/en-us/library/ms150046.aspx
*Not recommended way (with string manipulation):
If your jid's length is fix you can do the following:*
string url = driver.Url;
string jid = url.Substring(url.Length-8,8)
Console.WriteLine(jid);
Your example redone
string url = driver.Url;
string newUrl = url.Split('=').Last();
Console.WriteLine(newUrl);
Try this using string.Split
DotNetFiddle Example You can run
Here is the code from within the fiddle:
var URL = "http://.........../abc.aspx?JID=00001833";
var JID = URL.Split('?').Last();
Console.WriteLine(JID);
var JIDVal = JID.Split('=').Last();
Console.WriteLine(JIDVal);
i have the following set of Urls:
http://test/mediacenter/Photo Gallery/Conf 1/1.jpg
http://test/mediacenter/Photo Gallery/Conf 2/3.jpg
http://test/mediacenter/Photo Gallery/Conf 3/Conf 4/1.jpg
All i want to do is to extract the Conf 1, Conf 2,Conf 3 from the urls, the level after 'Photo Gallery' (Urls are not static, they share common level which is Photo Gallery)
Any help is appreciated
Is it necessary to use Regex? You can get it without using Regex like this
string str= #"http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
var z=qq.Split('/')[5];
or
var x= new Uri(str).Segments[3];
This ought to do you:
var s = #"http://test/mediacenter/Photo Gallery/Conf 11/1.jpg";
var regex = new Regex(#"(Conf \d*)");
var match = regex.Match(s);
Console.WriteLine(match.Groups[0].Value); // Prints a
Of course, you'd have to be confident the 'Conf x' (where x is a number) wasn't going to be elsewhere in the URL.
This will improve it slightly by stripping off multiple folders (Conf 3/Conf 4) in your example.
var regex = new Regex(#"((Conf \d*/*)+)");
It leaves the trailing / though.
No need for regex.
string testCase = "http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";
string urlBase = "http://test/mediacenter/Photo Gallery/";
if(!testCase.StartsWith(urlBase))
{
throw new Exception("URL supplied doesn't belong to base URL.");
}
Uri uriTestCase = new Uri(testCase);
Uri uriBase = new Uri(urlBase);
if(uriTestCase.Segments.Length > uriBase.Segments.Length)
{
System.Console.Out.WriteLine(uriTestCase.Segments[uriBase.Segments.Length]);
}
else
{
Console.Out.WriteLine("No child segment...");
}
Try a RegEx like this.
Conf[^\/]*
This should give you all "Conf" Parts of the URLs.
I hope that helps.
I tried to check matches facebook url and get profile in one regular expression:
I have:
http://www.facebook.com/profile.php?id=123456789
https://facebook.com/someusername
I need:
123456789
someusername
using this regular expression:
(?<=(https?://(www.)?facebook.com/(profile.php?id=)?))([^/#?]+)
I get:
profile.php
someusername
Whats wrong?
I advise you to use the System.Uri class to get this information. It does the difficult work for you and can handle all sorts of edge cases.
var profileUri = new Uri(#"http://www.facebook.com/profile.php?id=123456789");
var usernameUri = new Uri(#"https://facebook.com/someusername");
Console.Out.WriteLine(profileUri.Query); // prints "?id=123456789"
Console.Out.WriteLine(usernameUri.AbsolutePath); // prints "/someusername"
I agree with others on using System.Uri but your regex needs two modifications to work:
\ in (profile.php\?id=)
(\n|$) at the end
(?<=(https?://(www\.)?facebook\.com/(profile\.php\?id=)?))([^/#?]+)(\n|$)
The following example writes the query ?id=123456789 to the console.
Uri baseUri = new Uri ("http://www.facebook.com/");
Uri myUri = new Uri (baseUri, "/profile.php?id=123456789");
Console.WriteLine(myUri.Query);
Hope this Helps!
Try this:
https?://(?:www.)?facebook.com/(?:profile.php\?id=)?(.+)
or
https?://(?:www.)?facebook.com/(?:profile.php\?id=)?([^/#\?]+)
I'm resizing an image dynamically thus:
ImageJob i = new ImageJob(file, "~/eventimages/<guid>_<filename:A-Za-z0-9>.<ext>",
new ResizeSettings("width=200&height=133&format=jpg&crop=auto"));
i.Build();
I'm attempting to store the image relative URL in the DB. The i.FinalPath property gives me:
C:\inetpub\wwwroot\Church\eventimages\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg
How can I obtain just the image filename - best way to parse this?
Desired string: /eventimages/56b640bff5ba43e8aa161fff775c5f97_scenery.jpg
something like below,
var sitePath = MapPath(#"~");
var relativePath= i.FinalPath.Replace(sitePath, "~");
Just use Regular expressions
Regex.Match
Create you pattern and extract desired value
string input = "C:\\inetpub\\wwwroot\\Church\\eventimages\\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg";
Match match = Regex.Match(input, #"^C:\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\([A-Za-z0-9_]+\\[A-Za-z0-9_]+\.jpg)$", RegexOptions.IgnoreCase);
if (match.Success)
{
// Finally, we get the Group value and display it.
string path = match.Groups[1].Value.Replace("\\", "/");
}
Here is what I use in a utility method:
Uri uri1 = new Uri(i.FinalPath);
Uri uri2 = new Uri(HttpContext.Current.Server.MapPath("/"));
Uri relativeUri = uri2.MakeRelativeUri(uri1);
(stolen from someone else... can't remember who, but thanks)