tags:

views:

161

answers:

4

I would like a c# regex to determine if a string contains 5+ characters within a defined sequence.

Example: If the sequence was the alphabet then 'ghijk' would be true, while 'lmn' would be false.

Edit: The sequence needs to be in order. from example above 'ghijz' would return false.

+3  A: 
[a-zA-Z]{5,}
CptSkippy
This would match any string of 5 letters or more, but the OP needs the string to match a segment of the sequence, meaning the string must be in sequential order.
Jeff L
+7  A: 

You don't necessarily need a regular expression to accomplish this:

bool IsInSequence(string str, string sequence)
{
    return str != null && str.Length >= 5 && sequence.Contains(str);
}

Unless I'm missing what you're trying to accomplish here.

Jeff L
Greg Beech
I would like it to be a regex since the rest of the code is regex.
Thad
I can understand your desire for consistency, but in this case I think the regex-free solution is cleaner and simpler.
Jeff L
@Thad: In that case, consider changing chunks of the rest of the code to be free of un-needed regexs. Using regexes unnecessarily is bad practice.
Brian
+1  A: 

Use Contains() instead of a RegEx:

string sequence = "abcdef"
bool match = ("abcdefghijklmnopqrstuvwxyz".contains(sequence) 
                                     && sequence.Length >= 5);

You're better off without a regex for what you're doing.

Dan Herbert
+1  A: 

If the sequence needs to be in order, then what you're looking for can't be accomplished with regular expressions. Regular expressions can only perform pattern matching on characters, and can't place meaning (such as an ordering) on the sequence.

PFHayes