Regex for double values with comma and dot [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
void RandomRegex(object sender, TextCompositionEventArgs e)
{
var regex = new Regex("^[0-9]*$");
if (regex.IsMatch(e.Text) && !(e.Text == "," && ((TextBox)sender).Text.Contains(e.Text)))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
How can I change it that it also accepts 0,5 with a dot like this -> 0.5
EDIT: I use this Regex to avoid letters in TextBoxes like Height for example.

I think "[0-9,\\.]+" could work here.
var pattern = "[0-9,\\.]+";
foreach( var test in new [] {"0,5", "0.5", "", "abc"})
Console.WriteLine($"{test}: {Regex.IsMatch(test, pattern)}");
0,5: True
0.5: True
: False
abc: False
As others have pointed out you could make your number parsing better.
You could:
(probably preferred) use the user's culture; or
make number parsing more resilient instead.
foreach (var test in new[] { "0.5", "0,5", "2019,11", "2,019.11", "abc" })
{
var frenchR = decimal.TryParse(test, NumberStyles.AllowThousands|NumberStyles.AllowDecimalPoint, new CultureInfo("fr-FR"), out var dec );
bool? invariantR = null;
if( !frenchR )
invariantR = decimal.TryParse(test, NumberStyles.AllowThousands|NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dec );
//var dec2 = decimal.Parse(test, CultureInfo.InvariantCulture);
Console.WriteLine($"{test,10} => {dec,10} (french={frenchR}, invariant={(invariantR?.ToString()??"not attempted")})");
}
0.5 => 0.5 (french=False, invariant=True)
0,5 => 0.5 (french=True, invariant=not attempted)
2019,11 => 2019.11 (french=True, invariant=not attempted)
2,019.11 => 2019.11 (french=False, invariant=True)
abc => 0 (french=False, invariant=False)

Related

how to have a list of 'a' to 'z'? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a code that I want to count the number of appearing each letter in alphabet in the input string.
I used a dictionary<char, int> to have a key for each letter and a value as the count of appearance.
So, how to have a list of 'a' to 'z' to use as keys?
I've tried this:
Dictionary<char, int> alphabetCounter = new Dictionary<char, int>();
for (char ch = 'a'; ch <= 'z'; ch++)
alphabetCounter[ch] = 0;
Is it a better way to have the list of 'a' to 'z'?
Thank you.
Using Linq try this to have a list from "a" to "z".
var list = Enumerable.Range('a', 'z' - 'a' + 1).Select(c => (char)c).ToList();
If you want to get in upper case, is the same but using upper case.
var list = Enumerable.Range('A', 'Z' - 'A' + 1).Select(c => (char)c).ToList();
Edit:
Your question is to get the list, but to get as dictionary you can use .ToDictionary() and initialize with value 0:
var dictionary = Enumerable.Range('a', 'z' - 'a' + 1).Select(c => (char)c).ToDictionary(i => (char)i, i => 0);
The same case to upper/lower case.
Here's a way to do it in LINQ:
var alphabetCounter = Enumerable.Range(97, 26).ToDictionary(i => (char)i, i => 0);
This will create a dictionary with all chars with values 0.
ASCII codes of alphabet (lowercase) begins at 97, we can then take 26 numbers from there and convert them to char.
Is performance a thing? You can keep it simple.
You do not need to create your own dictionary, register every possibility then start counter[i]++ for each ocurrence, seems a bit of an overkill to me.
You can group up the letters by using .GroupBy (System.Linq), then after you can check the count of each ocurrence.
Example:
var word = "test";
var groupedLetters = word.GroupBy(x => x);
foreach(var letter in groupedLetters)
{
Console.WriteLine($"{letter.Key} - {letter.Count()}");
}
Output:
t - 2
e - 1
s - 1
Hi May this example will help :
List<char> LS = new List<char>() {'A', 'B', 'C', 'D', 'A', 'D', 'B', 'A'};
Dictionary<char,int> AlphaDictionary = (from x in LS group x by x).Select(x => new {Alpha = x.Key, Count = x.Count()}).ToDictionary(x=>x.Alpha,x=>x.Count);

Spliting string with multiple conditions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a string like this -
query = "UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\") AND CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z] OR FirstName: Abc ";
But I want to get the result in array like this -
queries=
{
[0] UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\")
[1] AND
[2] CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z]
[3] OR
[4] FirstName: Abc
}
Updates:
So far I had used this -
var result =
(from Match m in Regex.Matches(query , #"\[[^]]*]|\{[^}]*}|[^:]+")
select m.Value)
.ToArray();
But ended with this -
SOLUTION:
Based on the solution suggested by #NetMage I added some more variations to take care of double quotes, conditions inside parenthesis Here
UserId : ("787D01FE-D108-4C83-A2E2-4B1DA3166A5C" OR "CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C") AND CreatedDate : [ 2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z ] AND (FirstName : "Abc" OR LastName : "Xyz")
Regex Expression -
(?:\w+?\s*:\s*(\(.+?\)|\".+?\"|\[.+?\]|\w+))|(?:\(\w+?\s*:\s*(\(.+?\)|\".*?\"*|\[.+?\]|\w+)\))|([A-Z]+( [A-Z]+ )?)
How does this work for you?
var pattern = #"(?:\w+? ?: ?(\(.+?\)|\[.+?\]|\w+))|([A-Z]+( [A-Z]+ )?)";
var ans = Regex.Matches(query, pattern).Cast<Match>().Select(m => m.Value).ToArray();

How to validate a string contains at least 6 distinct digits using regex? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to get a Regex that checks to make sure that a supplied integer is 9 digits long and shall contain at least 6 non-repetitive digits
Example:
123456123 ------> Matches (6 different digits)
123243521 ------> Does not match (5 different digits)
This is much easier to do without a regex:
var str = "1234567890";
var isOk = str.Length >= 9
&& str.All(c => c >= '0' && c <= '9')
&& str.Distinct().Count() >= 6;

Float.Parse 0 value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Result:
0 0
0 0
-6361 0
-6384 -6672
0 0
0 -6793
...
Code:
string regex = #"X:(.*?)\sY:(.*?)";
if (File.Exists("minelist.log"))
File.Delete("minelist.log");
File.Copy(war3path + "\\minelist.log", "minelist.log");
string[] crdlist = File.ReadAllLines("minelist.log");
for (int i = 0; i < crdlist.Length;i++)
{
Match COORM = Regex.Match(crdlist[i], regex);
if (COORM.Success)
{
float x = 0.0f, y = 0.0f;
float.TryParse(COORM.Groups[1].Value, out x);
float.TryParse(COORM.Groups[2].Value, out y);
MessageBox.Show(x.ToString(), y.ToString());
}
}
if (File.Exists("minelist.log"))
File.Delete("minelist.log");
As a result, only certain values ​​are parsed. Others = 0.
FILE
Result:
0 0
0 0
6361 0
-6384 6672
0 0
0 -6793
...
Your RegEx is not matching what you think it's matching. You could have inspected the capture groups using MessageBox (or by stepping over in the debugger). The problem is you you used .*? to capture the group of digits: any number of any character, lazily; Then in the foreach loop you used TryParse() but did not check the result! On the lines you got "0" as a result, the regex probably stopped too soon. The TryParse() would fail and leave your X and Y to there default values.
Complete Console example properly parsing everything:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] crdlist = {
"X:-6625.5 Y:-6585.5",
"X:-6601.25 Y:-6703.75",
"X:-6361 Y:-6516.5",
"X:-6384 Y:-6672",
"X:-6400.25 Y:-6847.75",
"X:-6608.75 Y:-6793",
"X:-6739.75 Y:-6872",
"X:-6429.25 Y:-6940",
"X:-7015.5 Y:-6835.5",
"X:-7117 Y:-6903",
"X:-6885.5 Y:-6662.5",
"X:-6861.5 Y:-6597",
"X:-7006.5 Y:-6728",
"X:-7009 Y:-6608.75",
"X:-6924 Y:-6798",
"X:-6970.25 Y:-6898.25",
"X:-6495.25 Y:-6775",
"X:-7112.5 Y:-6614.5",
"X:-7115.25 Y:-6717.25",
"X:-7113.25 Y:-6835.5",
"X:-6493 Y:-6620.25"
};
Regex re = new Regex(#"^\ *X\:([\-\.0-9]*)\ *Y\:([\-\.0-9]*)\ *$", RegexOptions.Compiled);
var us_EN = new CultureInfo("en-US");
foreach(var line in crdlist)
{
Match m = re.Match(line);
if (m.Success)
{
String X = m.Groups[1].Value;
String Y = m.Groups[2].Value;
float fX = float.Parse(X, us_EN);
float fY = float.Parse(Y, us_EN);
Console.WriteLine("X={0}, Y={1}", fX, fY);
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
Use this regular expression pattern:
string regex = #"X:(-*d*.*d*)\sY:(-*d*.*d*)";

Detect bet regex [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When I receive a number I want to check it against all the potential bet combinations, e.g.
L( 24, 25, 26, 27)
Would return true if I was searching for the number 24 but not 2, hope I'm clear, sorry for no code I'm a newbie.
bool ChechResult(int value)
{
String input = #"L( 24, 25, 26, 27)";
String pattern = #"\d+";
foreach (Match match in Regex.Matches(input, pattern))
{
if(value == int.Parse(match.Value))
{
return true;
}
}
return false;
}
bool foundMatch = Regex.IsMatch(subject, " " + 24 + "(?:,|\\))");

Categories

Resources