I'm trying to come up with a c# regular expression that I originally
thought would be easy, but the solution is turning out to be much more
difficult. Basically, I need an expression that will match a string 9
characters in length that must contain at least 7 ones and no more than
two "stars" (*). The ones and stars can appear in any order. So, for
instance, all the following would be valid matches:
111111111
*11111111
*1111111*
1*111*111
1111**111
1111111**
etc.
The following would not be valid matches:
1*111**11
*1111***1
*********
11111111111
etc.
Any help would be appreciated.
I'm not entirely sure you can do this type of thing with an expression because using regex would allow the last two invalid matches to be valid.
BTW, the last invalid and the first valid match is the same. Which is invalid????
While I'm sure this could probably be handled with some crazy regex nested expression and capturing, I think it'd be pretty difficult. So, unless someone here is a regex god, I propose the following somewhat inefficient solution:
I tested it with .NET 2.0 with your examples, and they all worked.Code:static bool IsMatch(string s) { // Get length if ((s == null) || (s.Length != 9)) { return false; } // Must be between 7 and 9 1's string t = s.Replace(@"1",String.Empty); switch (9 - t.Length) { case 7: case 8: case 9: // Must have the remainder as *'s return (t.Replace(@"*",String.Empty).Length == 0); default: return false; } }
Hey,
That is a tough one. I agree with Brackett.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks