If we use the example string:
localhost:12345/MATCH_THIS_PART/more_strings
How would I return the value MATCH_THIS_PART and set it as the value of returnString. I think the problem can be solved using regex, and this is what I think would work:
string returnString = Regex.Match(Request.UrlReferrer.ToString(), #"not sure what goes here");
So basically, what goes in the part where I put
"not sure what goes here"
There are several options. String splitting is the easiest one:
string part = Request.UrlReferrer.ToString().Split('/')[1]; // gets the second item
Or use this regular expression and get the first capture:
.*?\/(.*?)\/.*
Related
I have a string which is basically a url something like APIPAth/resources/customers/SSNNumber/authorizations/contracts.
The SSNNumber can be of any value. Its the actual SSN number which I want to remove from the string and the string should look like APIPAth/resources/customers/authorizations/contracts.
I can't find a proper solution in which without hardcoding the word and removing the string
I tried using Find and Replace but I think the function would require the particular word
Looking at the URL you provided, it appears you only want to get rid of digits. You could accomplish that with this line:
var output = Regex.Replace(input, #"[\d]", string.Empty);
There are many ways to skin this cat depending on what stays static.
One way would be to split the url by separators and join them back
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
var items = new List<string>(url.Split('/'));
items.RemoveAt(3);
url = string.Join("/", items);
Another way would be to use Regex
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
url = Regex.Replace(url, #"/customers/[^/]+/authorizations/", "/customers/authorizations/")
If you elaborate on what you expect in a generic solution, i.e. what part stays static, then I can help you out better
If SSN in number then it has to have form of this 000 00 0000 means 9 digits consequents.
Took a string parse it by / and you get an array of elements lets say parsed
for(int i=0; i<parsed.length; i++){
if(parsed[i].length === 9){
...keep this i...
}
}
remove this parsed[i] from whole parsed and concat with /
I have an issue with a string containing the plus sign (+).
I want to split that string (or if there is some other way to solve my problem)
string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10";
string strpluslevel = "";
strpluslevel = ColumnPlusLevel;
string[] strpluslevel_lines = Regex.Split(strpluslevel, "+");
foreach (string line in strpluslevel_lines)
{
MessageBox.Show(line);
strpluslevel_summa = strpluslevel_summa + line;
}
MessageBox.Show(strpluslevel_summa, "summa sumarum");
The MessageBox is for my testing purpose.
Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign.
i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples.
(It comes form Another software and I cant edit the output from that software)
How can I find out what that pattern is that is being repeated?
That in this exampels is the +-J10 or +MJ or +PPL14.1
In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on.
Maybe im doing it wrong by using Split, maybe there is another solution.
Maybe I use Split in the wrong way.
Hope you understand my problem and the result I want.
Thanks for any advice.
/Tomas
How can I find out what that pattern is that is being repeated?
Maybe i didn't understand the requirement fully, but isn't it easy as:
string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries);
string first = tokens[0];
bool repeatingPattern = tokens.Skip(1).All(s => s == first);
If repeatingPattern is true you know that the pattern itself is first.
Can you maybe explain how the logic works
The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
You should use String.Split function :
string pattern = ColumnPlusLevel.Split("+")[0];
...but it is always a repeated pattern starting with the plus sign.
Why do you even need String.Split() here if the pattern always only repeats itself?
string input = #"+MJ+MJ+MJ";
int indexOfSecondPlus = input.IndexOf('+', 1);
string pattern = input.Remove(indexOfSecondPlus, input.Length - indexOfSecondPlus);
//pattern is now "+MJ"
No need of string split, no need to use LinQ
String has a method called Split which let's you split/divide the string based on a given character/character-set:
string givenString = "+-J10+-J10+-J10+-J10+-J10"'
string SplittedString = givenString.Split("+")[0] ///Here + is the character based on which the string would be splitted and 0 is the index number
string result = SplittedString.Replace("-","") //The mothod REPLACE replaces the given string with a targeted string,i added this so that you can get the numbers only from the string
How to get text before a symbol in string ? Any ideas?
e.g. acsbkjb/123kbvh/123jh/
get text before first - "/"
Try this
string ss = myString.Split('/')[0];
You can use Substring() method to get the required part of the string.
String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');
String text2="";
if(index>=0)
text2=text.Substring(0,index);
get substring like
youstring.Substring(0,yourstring.IndexOf('/'));
The IEnumerable approach
string str = "acsbkjb/123kbvh/123jh/";
var result = new string(str.TakeWhile(a => a != '/').ToArray());
Console.WriteLine(result);
If there are no forward slashes this works without need to check the return of IndexOf
EDIT Keep this answer just as an example because the efficiency of this approach is really worse. IndexOf works faster also if you add an if statement to check the return value.
string text = "acsbkjb/123kbvh/123jh/";
string text2 = text.Substring(0, text.IndexOf("/"));
I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?
I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?
Thanks.
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.
You can do:
string result = original.Substring(2);
decimal value = decimal.Parse(result);
Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.
Don't.
Instead, you should make .Net do the dirty work for you:
Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);
If, for some reason, you don't want a negative number, call Math.Abs.
All string operations return a new string, because string is immutable
I wouldn't use substring if you can avoid it. It would be much simpler to do something like:
string result = original.Replace("$", "").Replace("-", "");