This is my string "search=;pageid=62,67;categoryid=0;orderby=;showon=1" I want to get 62 and 67 separately, how can I do this?
The best way is to use RegEx. You can use this expression to get the optimized result:
(\d{2})
This RegEx finds all the numbers with 2 digits only.
You can use String.Split and a Lookup<TKey, TValue>:
var yourString = " search=;pageid=62,67;categoryid=0;orderby=;showon=1";
var lookup = yourString.Trim().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Split('='))
.ToLookup(arr => arr[0], arr => arr[1].Split(','));
string[] allPageIDs = lookup["pageid"].FirstOrDefault();
// allPageIDs can be null if the string didn't contain pageid
foreach (string id in allPageIDs)
Console.WriteLine(id);
A lookup is similar to a dictionary but it if the input sequence contains the key multiple times no exception is raised but the value contains all results. Therefore FirstOrDefault above returns the first result which is a string[] with two values 62,67 in this case.
Related
I need a regex which validate string of numbers either math "aabb" or "abba" pattern.
For example: both 1122 or 1221 is valid
Regex for both "aabb", "abba" worked fine alone.
But when i'm trying to combine "aabb" OR "abba", the result of "aabb" is always false.
(1122 returned not valid)
Here is my implementation in C#:
string phoneNumber = "1221"; // "1122" failed
Dictionary<string, string> subPatterns = new Dictionary<string, string>();
subPatterns[#"(\d)(\d)\2\1$"] = "abba";
subPatterns[#"(\d)\1(\d)\2$"] = "aabb";
string pattern = string.Join("|", subPatterns.Select(e => e.Key));
foreach (Match m in Regex.Matches(phoneNumber, pattern))
{
if (m.Success)
{
Console.WriteLine("TRUE");
}
}
Did i missed something?
The alternation changes the capture group numbers. You can either account for the incremented numbers in the alternation:
subPatterns[#"(\d)(\d)\2\1$"] = "abba";
subPatterns[#"(\d)\3(\d)\4$"] = "aabb";
The pattern will look like this, matching the 4 digits at the end of the string due to the $
(\d)(\d)\2\1$|(\d)\3(\d)\4$
Or you can use the same named backreferences:
subPatterns[#"(?<1>\d)\k<1>(?<2>\d)\k<2>"] = "abba";
subPatterns[#"(?<1>\d)(?<2>\d)\k<2>\k<1>"] = "aabb";
The pattern will then look like
(?<1>\d)(?<2>\d)\k<2>\k<1>|(?<1>\d)\k<1>(?<2>\d)\k<2>
Note that if the matches are for the whole line, you can append an anchor ^ to it and the whole pattern will look like
^(?:(?<1>\d)(?<2>\d)\k<2>\k<1>|(?<1>\d)\k<1>(?<2>\d)\k<2>)$
See a regex demo and a C# demo.
I have textbox1 field in asp.net and a text area to show count of records.
I want to count the records split by , in textbox1 but when textbox1 is empty text area is showing 1.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
String.Split always returns at least one string, if you pass string.Empty you will get one string which is the input string(so in this case string.Empty).
Documentation:
....
If this instance does not contain any of the characters in separator,
the returned array consists of a single element that contains this instance.
You have to check it, f.e. with string.IsNullOrEmpty(or String.IsNullOrWhiteSpace):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
Try this
int contacts = string.IsNullOrEmpty(string.textbox1.Text)? string.empty: textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
This is because even when textbox1.Text is an empty string, that's still treated as one item. You need to use StringSplitOptions.RemoveEmptyEntries so that empty entries are ignored when producing the result of calling Split:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you've written into individual statements, what you have is:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look at items you'll see that it's an array of strings (string[]) which contains one entry for each item in the text from textbox1.Text.
Even if an empty string is passed in (i.e. textbox1 is empty) there's still one string to be returned, hence the fact that your code as written is returning 1, whereas in countOfItems where I've broken the code apart it will have 0 because of the use of StringSplitOptions.RemoveEmptyEntries.
The documentation on msdn of the String.Split overload that takes StringSplitOptions as a parameter has more examples and detail about this.
what is wrong with this code?
bool claimExists;
string currentClaimControlNo = "700209308399870";
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
claimExists = true;
else
claimExists = false;
Why the claimControlNo above is coming into false?
Since I know the value exists, how can i tune the code?
It's reporting false because you aren't asking whether the list contains the currentClaimControlNo, you're asking whether it contains a string that is the first fourteen characters of the fifteen-character string currentClaimControlNo.
Try this instead:
claimExists = claimControlNo.Any(ccn => ccn.StartsWith(currentClaimControlNo.Substring(0,14)));
Your count is wrong. There are 15 characters. Your substring is cutting off the last 0 which fails the condition.
Because you're shaving off the last digit in your substring.
if you change the line
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
to
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 15)))
it works.
Because contains on a list looks for the whole item, not a substring:
currentClaimControlNo.Substring(0, 14)
"70020930839987"
Is not the same as
700209308399870
You're missing a digit, hence why your list search is failing.
I think you are trying to find something in the list that contains that substring. Don't use the lists contain method. If you are trying to find something in the list that has the subset do this
claimExists = claimControlNo.Any(item => item.Contains(currentClaimControlNo.Substring(0, 14)))
This goes through each item in claimControlNo and each item can then check if it contains the substring.
Why do it this way? The Contains method on a string
Returns a value indicating whether the specified System.String object occurs within this string.
Which is what you want.
Contains on a list, however
Determines whether an element is in the System.Collections.Generic.List.
They aren't the same, hence your confusion
Do you really need this explaining?
You are calling Substring for 14 characters when the string is of length 15. Then you are checking if your list (which only has one item of length 15) contains an item of length 14. It doesn;t event need to check the value, the length is enough to determine it is not a match.
The solution of course is to not do the Substring, it makes not sense.
Which would look like this:
if (claimControlNo.Contains(currentClaimControlNo))
claimExists = true;
else
claimExists = false;
Then again, perhaps you know you are trimming the search, and are in fact looking for anything that has a partial match within the list?
If this is the case, then you can simply loop the list and do a Contains on each item. Something like this:
bool claimExists = false;
string searchString = currentClaimControlNo.Substring(0, 14);
foreach(var s in claimControlNo)
{
if(s.Contains(searchString))
{
claimExists = true;
break;
}
}
Or use some slightly complex (certainly more complex then I can remember off the top of my head) LINQ query. Quick guess (it's probably right to be fair, I am pretty freaking awesome):
bool claimExists = claimControlNo.Any(x => x.Contains(searchString));
Check it:
// str will be equal to 70020930839987
var str = currentClaimControlNo.Substring(0, 14);
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
The value str isn't contained in the list.
Coming from perl, I'm I bit confused by the asp.net regex classes.
I have a simple pattern I'm trying to match: "number text number"
My code looks like:
Match results = Regex.Match(mystring, #"(\d+)\s+(Highway|Hwy|Route|Rte)\s+(\d+)",RegexOptions.IgnoreCase);
foreach (Group g in results.Groups)
{
string token = g.Value;
}
The problem is that the groups seems to contain 4 results, not the 3 I would expect - the first is the entire string that gets matched, while the next 3 are what I would expect.
Is there a simple way to directly access my 3 results?
You could use Matches:
// Define a test string.
string text = "The the quick brown fox fox jumped over the lazy dog dog.";
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);
// Report on each match.
foreach (Match match in matches)
{
...
}
var results = Regex.Match("55 Hwy 66", #"(\d+)\s+(Highway|Hwy|Route|Rte)\s+(\d+)", RegexOptions.IgnoreCase).Groups.OfType<Group>().Select((name, index) => new {name, index}).Where(x => x.index > 0).Select(x => x.name).ToList();
This is just a case of how it is designed to work, and it is just a case of ignoring the first match. I do agree that it is a strange implementation and not how I would have expected it to work.
If the regular expression engine can find a match, the first element of the GroupCollection object returned by the Groups property contains a string that matches the entire regular expression pattern.
Taken from here
I know this is an old question, but I ended up here through a search confirming my own thoughts and there was no definitive answer.
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function