|
They aren't that difficult to compose, they are just nasty to read!
Have a look at this: Expresso[^] - it's free, and it examines, explains, and generates Regular expressions. It even creates the C# or VB code for you to use them.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
You could write an extension method to get the string between the delimiters:
public static string BetweenChars(this string text, char left, char right)
{
string result = string.Empty;
int leftPos = text.IndexOf(left, 0)+1;
int rightPos = text.LastIndexOf(right);
if (leftPos >= 0 && rightPos > leftPos)
{
result = text.Substring(leftPos, rightPos - leftPos);
}
return result;
}
Or one to just get the delimiter positions
public static void DelimiterPos(this string text, char left, char right, out int leftPos, out int rightPos)
{
string result = string.Empty;
leftPos = text.IndexOf(left, 0);
rightPos = text.LastIndexOf(right);
}
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Thank you all. I will tryout all of your suggestions and see which one suits my needs.
|
|
|
|
|
Hi, I need help. Is it possible to compare two textboxes first then display if they are the same or not in another textbox. this is what I have so far:
if (textBox1.TextLength == 3)
{
textBox2.Focus();
}
if (textBox2.TextLength == 3)
{
textBox1.Focus();
}
if (textBox1.Text == textBox2.Text)
{
textBox3.Text = "PASSED";
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
if (textBox1.Text != textBox2.Text)
{
textBox3.Text = "FAILED";
}
My issue here is that the moment I input something in textbox1, textbox3 will show FAILED already.
Thanks in advance.
BTW, I cant use btnclick event.
|
|
|
|
|
This is really a state machine but not written like one, so probably you got confused about what state to do what in, so everything happens all the time.
I don't really know either, because you don't say how it should work, but maybe it's meant to work like this:
state 0 [entry]: textbox 1 is focused (refocus if it loses focus?). If the text length reaches 3, go to state 1. Maybe do something about length > 3 too, such as cut off the extra and then go to state 1.
state 1: textbox 2 is focused (refocus as needed). If the text length reaches 3, compare text. If passed, clear boxes, put PASSED in box 3, and go to state 0. If failed, go to state 2.
state 2: put FAILED in box 3 and just die or something, not clear from your code what should happen here. Maybe allow box 2 to be edited until pass? Who knows.
|
|
|
|
|
Your code doesn't make any sense.
I assume you're using the TextChanged event to determine when to compare the two fields (if you're not, you should be).
When the text in one text box or the other changes, it should be immediately compared against the text box, and the SECOND textbox should be highlighted as invalid if the contents don't match (because any sane person would assume the first text box is the determining factor).
Further, I'm not sure why you're clearing the contents on the text boxes when in a "PASS" condition, but whatever.
Lastly, you shouldn't be programmatically changing focus between controls unless it makes sense to do so (form initialization, or process-specific control selection by the user).
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Please use the pre tags when adding code snippets (the code button in the toolbar)
I think you want something like this:
if (textBox1.TextLength == 3)
{
textBox2.Focus();
}
if (textBox2.TextLength == 3)
{
textBox1.Focus();
}
if(textbox1.TextLength == 3 && textbox2.TextLength == 3){
if (textBox1.Text == textBox2.Text)
{
textBox3.Text = "PASSED";
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
if (textBox1.Text != textBox2.Text)
{
textBox3.Text = "FAILED";
}
}
Quote: BTW, I cant use btnclick event.
I have no idea what you want this statement...
hope this helps.
|
|
|
|
|
2 assume their respective control dateEdit: dEditForm and dEditTo want to check the date of this control has the form 2: date from: "__ / __ / ____" and date to: 11/09/2016, which from day null and days to 1 day, must be valid as examples here dates are September 11 years his 2016 writing test code with the error message:
[CODE]
if (dEditFrom.DateTime == null && dEditTo.DateTime != null) // warning error here dEditTo.DateTime != null
{ do something ... }
[/CODE]
I using devexpress. can you help me ?
|
|
|
|
|
No, I can't - because I have no idea what you are trying to do, or how it is giving you difficulties.
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work from.
So explain in more detail exactly where it's a problem, and if there is an error message then tell us exactly what it says - copy and paste it from VS.
Show us the code that gives a problem (again, copy and paste here) and explain what it does that you didn't expect, or doesn't do that you did.
At the moment I have no idea, especially as the DateTime property of a devexpress DateEdit control is a .NET DateTime value - which is a struct, and this can't be null.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
If you're using DevExpress, doesn't it already validate as you type the date?
Generally speaking, you can validate a date entry field by using DateTime.TryParse() . If TryParse returns false, the text does not represent a valid DateTime object.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
I have been working on finding case numbers in strings based on user inputted pattern. The pattern is build up by using the Characters D=Decimal , A=Aplha ,- = seperator.
This can be anywhere from DDDAAAA or DDDD-AAAA-DA-AD, most common case would be DDDD-DDDD or DDAA-DDDD , Note that a separator is not mandatory.
I have written an old-school void that creates a list of strings that represent the sequences in the pattern. For the pattern DDAA-DDD i would return this.
new List {DD,AA,-,DDD}
And then use the list to find my matches (different story)
Q: I have been trying to figure out how to do this using linq queries.
What I have so far is sort of on point, but only partialy.
var pattern = "DDDD-AA-DD";
var patternlist = pattern.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Element = y, Counter = y.Count() });
This will not create a separate group for all the patterns or sequences. This will only tell me that I have 6 instances of D , 2 instances of A and 2 instances of -.
I wanted to find an elegant solution to this, where I could return something like a group per sequence of a char. Note I would not want to use the values of the chars or reference the known values.
I’m not looking for something like this.
if (pattern.StartsWith("A"))
{
var tst = pattern.TakeWhile(p => p == 'C');
}
Any takers
|
|
|
|
|
I don't think the built-in LINQ methods will help you here. But it's fairly simple to implement:
public static class Patterns
{
public static IEnumerable<string> GroupPatterns(this string pattern)
{
char prev = '\0';
char[] item = new char[pattern.Length];
int itemIndex = 0;
foreach (char c in pattern)
{
if (c != prev)
{
if (itemIndex != 0)
{
yield return new string(item, 0, itemIndex);
Array.Clear(item, 0, itemIndex);
itemIndex = 0;
}
prev = c;
}
item[itemIndex] = c;
itemIndex++;
}
if (itemIndex != 0)
{
yield return new string(item, 0, itemIndex);
}
}
}
Given the input "DDDD-AAAA-DA-AD" , that will produce:
{
"DDDD",
"-",
"AAAA",
"-",
"D",
"A",
"-",
"A",
"D"
}
As to finding the matches, it might be simpler to convert the pattern to a Regular Expression[^]:
public static class Patterns
{
...
public static Regex PatternToRegularExpression(this string pattern)
{
var parts = new List<string>();
foreach (string part in pattern.GroupPattern())
{
switch (part[0])
{
case 'D':
case 'd':
{
parts.Add("\\d{" + part.Length + "}");
break;
}
case 'A':
case 'a':
{
parts.Add("[A-Z]{" + part.Length + "}");
break;
}
default:
{
parts.Add(Regex.Escape(part));
break;
}
}
}
string regexPattern = string.Concat(parts);
return new Regex(regexPattern, RegexOptions.IgnoreCase);
}
}
For the same input, this will generate the regular expression:
\d{4}-[a-z]{4}-\d{1}[a-z]{1}-[a-z]{1}\d{1}
Regexper[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
thaks for your input, 
|
|
|
|
|
LINQ isn't always the answer. This is the way I'd do it.
List<string> patternList = new List<string>();
foreach(char ch in pattern)
{
if (patternList.Count == 0 || !patternList.Last().Contains(ch))
{
patternList.Add(ch.ToString());
}
else
{
patternList[patternList.Count-1] += ch.ToString();
}
}
You could put this code into an extension method.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Granted, and my solution is not a linq solution , but i started by using linq, and was surprised that this was not possible by default.
|
|
|
|
|
It's truly an issue of using the right tool for the job. While Richard's solution is indeed "LINQy", that's an awful lot of code to adhere to your requirement of being able to group characters in a string into separate strings by character.
I've seen guys get stumped for days at a time because they were trying to be "elegant". Brute force is where it's at.
EDIT ==========
Richard's solution wasn't LINQy after all.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
modified 9-Sep-16 8:38am.
|
|
|
|
|
hehe... been there so many times..
|
|
|
|
|
John Simmons / outlaw programmer wrote: patternList.Last()
Hey, I thought you were avoiding LINQ!
John Simmons / outlaw programmer wrote: patternList[patternList.Count-1] += ch.ToString();
String concatenation in a loop - because that never affects the performance of your code at all.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: Hey, I thought you were avoiding LINQ!
More accurately, I didn't say to avoid LINQ, I said LINQ wasn't appropriate the way he was trying to do it. Going out of your way to avoid a specific construct is almost as pointless as going out of your way to only use that construct. Getting the work done is much more important.
Richard Deeming wrote: String concatenation in a loop - because that never affects the performance of your code at all.
I could have done this, but I'm at work and didn't feel like retyping it. I'm pretty lazy.
patternList[patternList.Count-1] = string.Format("{0}{1}", patternList[patternList.Count-1], ch);
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
But that's even worse!
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Micro-optimizations are pointless when you're dealing with strings this small, with probably few (if any) repetitive calls to the method containing this code.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
 Here is my simple test utility that i used to test my code. It's not elegant but does the job.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace TestSubjectMatterReco
{
class Program
{
static void Main(string[] args)
{
bool run = true;
while (run)
{
Console.WriteLine("Add string to use");
string subject = Console.ReadLine();
Console.WriteLine("Add Pattern Line to use");
string Pattern = Console.ReadLine();
var sout = Parse(subject, Pattern);
if (sout.Count() == 0)
Console.WriteLine("Unable to detect pattern");
else
{
int i = 1;
sout.ForEach(p => { Console.WriteLine($"found pattern {p} this is pattern nr {i} of {sout.Count()}"); i++; });
}
Console.WriteLine("----------------------------------");
Console.WriteLine();
Console.WriteLine("Press enter to try again , use q to qwuit");
var answer = Console.ReadLine();
if (answer=="q")
run = false;
}
}
static List<string> Parse(string subject, string pattern)
{
var subjectList = subject.Split(' ').ToList().Where(p => p.Length == pattern.Length).ToList();
string result = "";
if (subjectList.Count() > 0)
{
#region break down pattern
List<string> _patterns = new List<string>();
string patt = string.Empty;
int currindex = 0;
foreach (char c in pattern.ToCharArray())
{
currindex++;
if (patt == string.Empty)
patt = c.ToString();
else
{
if (patt.StartsWith(c.ToString()))
patt += c.ToString();
else
{
_patterns.Add(patt);
patt = c.ToString();
}
}
if(currindex == pattern.Length)
_patterns.Add(patt);
}
int indexinSubjct = 0;
#endregion
#region try to find text that fits the pattern
foreach (string pair in _patterns)
{
for (int j = subjectList.Count; j > 0; j--)
{
if (pair.StartsWith("D"))
{
if (!ParseDigit(subjectList[j-1].Substring(indexinSubjct, pair.Length)))
subjectList.Remove(subjectList[j-1]);
}
else if (pair.StartsWith("A"))
{
if (!ParseLetter(subjectList[j-1].Substring(indexinSubjct, pair.Length)))
subjectList.Remove(subjectList[j-1]);
}
else
{
string part = subjectList[j - 1].Substring(indexinSubjct, pair.Length);
if(part != pair)
subjectList.Remove(subjectList[j - 1]);
}
}
indexinSubjct += pair.Length;
}
return subjectList;
}
return new List<string>();
#endregion
}
static bool ParseLetter(string sequence)
{
return sequence.All(p => char.IsLetter(p));
}
static bool ParseDigit(string sequence)
{
return sequence.All(p => char.IsDigit(p));
}
}
}
|
|
|
|
|
var pattern = "DDDD-AA-DD";
while ( pattern.Length > 0 ) {
char ch1 = pattern[ 0 ];
string item = string.Join( "", pattern.TakeWhile( p => p == ch1 ) );
pattern = pattern.TrimStart( ch1 );
Console.WriteLine( item );
}
|
|
|
|
|
Attention Member 12106926: Please note the code shown here was written a few years ago, and has not been tested, recently. I would strongly advise you to use this code (if you find it useful) only as the basis for your own code, and, as always, to test thoroughly. Well, Sir, I am reluctant to step up to the plate when heavy-hitters like Simmons and Deeming are in the ... I'll be lucky if I don't get brained by a curvew-ball, let alone strike-out with both of them, but, I like to try and create generic solutions to tasks like cleaning-up (getting rid of unwanted whatevers at the start and end of a collection), and parsing. Here's a generic parser based on Extension Methods that will parse the OP's sample, producing an IEnumerable of List<char>:
public static class IEnumerableExtensions
{
public static IEnumerable<List<T1>> GroupByContiguous<T1>(this IEnumerable<T1> src, T1 delimiter)
{
var src1 = src.TrimStart<T1>(delimiter)
.TrimEnd<T1>(delimiter);
List<T1> srcList = src1.ToList();
T1 current;
T1 previous = srcList.First();
List<T1> element = new List<T1>();
element.Add(previous);
for (int i = 1; i < srcList.Count; i++)
{
current = srcList[i];
if (current.Equals(delimiter))
{
previous = delimiter;
continue;
}
if (! current.Equals(previous))
{
yield return element;
element = new List<T1>();
previous = current;
}
element.Add(current);
}
if (element.Count > 0) yield return element;
}
public static IEnumerable<T> TrimStart<T>(this IEnumerable<T> totrim, T trimthis)
{
return totrim.SkipWhile(itm => itm.Equals(trimthis));
}
public static IEnumerable<T> TrimEnd<T>(this IEnumerable<T> totrim, T trimthis)
{
return totrim.Reverse().SkipWhile(itm => itm.Equals(trimthis)).Reverse();
}
} Test with OP's data (with some extra delimiters thrown in for variety):
private string text = "-DDDD-AAAA-DAAD-ADDDAA---";
var parsedChars = text.GroupByContiguous<char>(delimiter: '-').ToList();
foreach (var grp in parsedChars)
{
Console.WriteLine(new string(grp.ToArray()));
}
DDDD
AAAA
D
AA
D
A
DDD
AA I've tested on basic ValueType and had no errors, but, an obvious issue when you start comparing complex objects (like instances of Classes) is: will using .Equals for the equality test suffice, or will you have to provide a custom implementation of IComparer.
«There is a spectrum, from "clearly desirable behaviour," to "possibly dodgy behavior that still makes some sense," to "clearly undesirable behavior." We try to make the latter into warnings or, better, errors. But stuff that is in the middle category you don’t want to restrict unless there is a clear way to work around it.» Eric Lippert, May 14, 2008
|
|
|
|
|
I think he wanted to know where the delimiters were as well.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|