+ Reply to Thread
Results 1 to 4 of 4

Thread: c# regular expression

  1. #1
    Learning Programmer moonrise is an unknown quantity at this point
    Join Date
    May 2006
    Posts
    40

    c# regular expression

    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.

  2. #2
    Programming Expert Crane is on a distinguished road Crane's Avatar
    Join Date
    Nov 2005
    Posts
    399
    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????

  3. #3
    Programmer brackett is on a distinguished road
    Join Date
    May 2006
    Posts
    193
    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:

    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;
       }
    }
    I tested it with .NET 2.0 with your examples, and they all worked.

  4. #4
    Programming Expert Crane is on a distinguished road Crane's Avatar
    Join Date
    Nov 2005
    Posts
    399
    Hey,
    That is a tough one. I agree with Brackett.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. Replies: 1
    Last Post: 07-16-2007, 08:18 PM
  2. Regular expressions
    By Nightracer in forum General Programming
    Replies: 6
    Last Post: 07-24-2006, 09:57 PM

Bookmarks

Bookmarks

     
        Algorithms and Data Structures

        Java tutorials

        Algorithms Forum

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts