Split a string so that it loses http:// and anything after the '.' - c#

I need to parse a url so that only my server shows "NA30" However when I'm doing the split I cant seem to just get the na30. I have tried trimming with '.' and '/' and i think I'm just getting the array parts wrong. Any guidance?
Link
https://na30.salesforce.com
What I'm currently working on
string thisUrl;
if (Helper.InstanceUrl.Contains(#"://"))
{
thisUrl = Helper.InstanceUrl.Split(new[] { "://" }, 2, StringSplitOptions.None)[1];
return thisUrl.Split('/')[0].Split('.')[0];
}
return "";

You can also find your string with the Uri class
Uri u = new Uri("https://na30.salesforce.com");
Console.WriteLine(u.Host.Split('.')[0]);
A worth question to read about is What's the difference between Uri.Host and Uri.Authority

You can use a regex to keep only the first part of the domain.
Regex.Match(url, #"//([^\.]+)").Groups[1].Value
http://rextester.com/URF41242

Related

How can I make a string out of a complex URL address

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();

Fetching a segment of the URL in the address bar

This is what I tried:
string myURL= "http://mysite.com/articles/healthrelated";
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
I need to fetch "healthrelated" ie the text after the last slash in the URL. Now the problem is that my URL can also be like :
"http://mysite.com/articles/healthrelated/"
ie "a Slash" at the end of that text too. Now the last slash becomes the one AFTER "healthrelated" and so the result I get using
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
is empty string..
what should my code be like so I always get that text "healthrelated" no matter if there's a slash in the end or not. I just need to fetch that text somehow.
Try this.
var lastSegment = url
.Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Last();
Why don't you use Uri class of .NET and use segments property:
http://msdn.microsoft.com/en-us/library/system.uri.segments.aspx
What you can do in this situation is either using REGEX (which I'm not an expert on, but I'm shure other ppl here are ;) ) or a simple:
string[] urlParts = myURL.Split('/');
and take the last string in this array.

trim url string. c#

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]

Querystring Issue on C# with special characters

I came across a very weird issue where in my querystirng had "++" as part of the text. but when i assign the query stirng value to a string ++ will become two spaces. How do i get exactly what is being passed as querystring?
I observed that the querystirng collection had "++" but when I do Request.QueryString["search"].ToString() "++" gone, I checked in Immediate window.
I use C# 2.0
URL: /default.aspx?search=test++
string t = Request.QueryString["search"].ToString();
You should use UrlEncode and UrlDecode
Those methods should be used any time you're inserting user inputted data into the query string.
'+' is reserved in query strings.
Within a query component, the
characters ";", "/", "?", ":", "#",
"&", "=", "+", ",", and "$" are
reserved.
Try using UrlEncode to encode your query strings.
A plus sign in a query string translates to a space. If you want an actual plus sign rather than a space, use %2B instead.
/default.aspx?search=test%2B%2B
If you're doing this in code, then you should be using UrlEncode to encode this portion of the query string.
I don't know that there's a way to get the exact text passed into the query. The HTTP standards basically say that a + is equivalent to a space character, so if you want to preserve the + you should encode the query string, as Chuck said.
The only solution I found was in this post HERE:
private string GetQueryStringValueFromRawUrl(string queryStringKey)
{
var currentUri = new Uri(HttpContext.Request.Url.Scheme + "://" +
HttpContext.Request.Url.Authority +
HttpContext.Request.RawUrl);
var queryStringCollection = HttpUtility.ParseQueryString((currentUri).Query);
return queryStringCollection.Get(queryStringKey);
}
Working on a ASP.Net 2.0 soluton, I had to do the following:
private string GetParameterFromRawUrl(string parameter)
{
var rawUrl = Request.RawUrl;
int indexOfParam = rawUrl.IndexOf(parameter);
int indexOfNextParam = rawUrl.IndexOf('&', indexOfParam);
string result;
if (indexOfNextParam < 1)
{
result = rawUrl.Substring(indexOfParam);
}
else
{
result = rawUrl.Substring(indexOfParam, (indexOfNextParam-indexOfParam));
}
return result;
}

how to get a text from textbox that is betwen two dots

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();

Categories

Resources