Reputation: 1679
I have 2 strings and want to know
if string 2 have a subset of the characters of string 1 on the same order
this subset has a minimun size determined by me.
For example:
string 1 = stackoverflow
<br>minimun size = 5
string 2a = stack (MATCH)
string 2b = stac (DO NOT MATCH)
string 2c = staov (MATCH)
string 2d = staZov (DO NOT MATCH)
string 2e = eflow (MATCH)
string 2f = ewolf (DO NOT MATCH)
string 2g = somethingstacksomething (MATCH)
I am building the regex programatically, so the first part of the problem could be solved with the expression: (s)?(t)?(a)?(c)?(k)?(o)?(v)?(e)?(r)?(f)?(l)?(o)?(w)?
But i can't figure out how to apply the "minimun character" rule. Is it possible to do it using regex?
thanks in advance!
EDIT: Added another example to complete the problem specification. Also, if you want to know, this is part of a method to evaluate the password strength specified by a user. If he defines a password derived from some other information (login, born date, name, etc) we should warn him.
Upvotes: 3
Views: 1397
Reputation: 34395
Interesting question! There is a way to do it, (but you aren't going to like it). It results in a potentially large (and possibly slow) regex. Assuming string1
is ABCD
. Then here are the regexes for all the different length requirements:
length = 4;
regex = @"
ABCD
";
length = 3;
regex = @"
ABCD?
| ABC?D
| AB?CD
| A?BCD
";
length = 2;
regex = @"
ABC?D?
| AB?CD?
| AB?C?D
| A?BCD?
| A?BC?D
| A?B?CD
";
length = 1
regex = @"
[ABCD]
";
I haven't thought through the way you would go about assembling this programmatically, but I'm sure that it can be done. However, a large regex having lots of OR'ed alternatives may likely be slower that using the "match then check the length of the matched string" method you are currently using.
I scratched my head for quite a while on this one and I'm pretty sure there is no simple/clever regex construct that does what you are asking.
Upvotes: 1
Reputation: 2548
But i can't figure out how to apply the "minimun character" rule.
After you determine the possible matches. You need to determine the length of the result.
You can simply use String.Length to determine that.
Upvotes: 2
Reputation: 887807
You could add a lookahead that ensures that there are five characters: (?=.{5})s?t?a?c?k?o?v?e?r?f?l?o?w?
Upvotes: 2