C# Regex Validation Rule using Regex.Match()












21















I've written a Regular expression which should validate a string using the following rules:




  1. The first four characters must be alphanumeric.

  2. The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.


So the string should look like this if its valid:




CCCCNNNNNN or CCCCNNNNNNN




C being any character and N being a number.



My expression is written: @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";



My regex match code looks like this:



var cc1 = "FOOBAR"; // should fail.
var cc2 = "AAAA1111111111"; // should succeed

var regex = @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";

Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );

if ( cc1 != string.Empty && match.Success )
{
//"The Number must start with 4 letters and contain no numbers.",
Error = SeverityType.Error
}


I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.



Also, am I use .Match() correctly? If Match.Success is true, then does that mean that the string is valid?










share|improve this question





























    21















    I've written a Regular expression which should validate a string using the following rules:




    1. The first four characters must be alphanumeric.

    2. The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.


    So the string should look like this if its valid:




    CCCCNNNNNN or CCCCNNNNNNN




    C being any character and N being a number.



    My expression is written: @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";



    My regex match code looks like this:



    var cc1 = "FOOBAR"; // should fail.
    var cc2 = "AAAA1111111111"; // should succeed

    var regex = @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";

    Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );

    if ( cc1 != string.Empty && match.Success )
    {
    //"The Number must start with 4 letters and contain no numbers.",
    Error = SeverityType.Error
    }


    I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.



    Also, am I use .Match() correctly? If Match.Success is true, then does that mean that the string is valid?










    share|improve this question



























      21












      21








      21


      5






      I've written a Regular expression which should validate a string using the following rules:




      1. The first four characters must be alphanumeric.

      2. The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.


      So the string should look like this if its valid:




      CCCCNNNNNN or CCCCNNNNNNN




      C being any character and N being a number.



      My expression is written: @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";



      My regex match code looks like this:



      var cc1 = "FOOBAR"; // should fail.
      var cc2 = "AAAA1111111111"; // should succeed

      var regex = @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";

      Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );

      if ( cc1 != string.Empty && match.Success )
      {
      //"The Number must start with 4 letters and contain no numbers.",
      Error = SeverityType.Error
      }


      I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.



      Also, am I use .Match() correctly? If Match.Success is true, then does that mean that the string is valid?










      share|improve this question
















      I've written a Regular expression which should validate a string using the following rules:




      1. The first four characters must be alphanumeric.

      2. The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.


      So the string should look like this if its valid:




      CCCCNNNNNN or CCCCNNNNNNN




      C being any character and N being a number.



      My expression is written: @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";



      My regex match code looks like this:



      var cc1 = "FOOBAR"; // should fail.
      var cc2 = "AAAA1111111111"; // should succeed

      var regex = @"^[0-9A-Za-z]{3}[0-9A-Za-z-]d{0,21}$";

      Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );

      if ( cc1 != string.Empty && match.Success )
      {
      //"The Number must start with 4 letters and contain no numbers.",
      Error = SeverityType.Error
      }


      I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.



      Also, am I use .Match() correctly? If Match.Success is true, then does that mean that the string is valid?







      c# regex validation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 6 '12 at 21:38









      dtb

      171k26344402




      171k26344402










      asked Jan 6 '12 at 21:35









      nocarriernocarrier

      1,27422954




      1,27422954
























          5 Answers
          5






          active

          oldest

          votes


















          34














          The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:



          var regex = @"^w{4}d{6,7}$";


          See: Regular Expression Language - Quick Reference





          The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.



          var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

          if (!match.Success)
          {
          // does not match
          }





          share|improve this answer

































            5














            The following code demonstrates the regex usage:



                    var cc1 = "FOOBAR"; // should fail.
            var cc2 = "AAAA1111111"; // should succeed
            var r = new Regex(@"^[0-9a-zA-Z]{4}d{6,7}$");
            if (!r.IsMatch(cc2))
            {
            Console.WriteLine("cc2 doesn't match");
            }
            if (!r.IsMatch(cc1))
            {
            Console.WriteLine("cc1 doesn't match");
            }


            The output will be cc1 doesn't match.






            share|improve this answer































              4














              The following code is using a regular expression and checks 4 different patterns to test it, see output below:



              using System;
              using System.Text.RegularExpressions;
              public class Program
              {
              public static void Main()
              {
              var p1 = "aaaa999999";
              CheckMatch(p1);
              p1 = "aaaa9999999";
              CheckMatch(p1);
              p1 = "aaaa99999999";
              CheckMatch(p1);
              p1 = "aaa999999";
              CheckMatch(p1);
              }

              public static void CheckMatch(string p1)
              {
              var reg = new Regex(@"^w{4}d{6,7}$");
              if (!reg.IsMatch(p1))
              {
              Console.WriteLine($"{p1} doesn't match");
              }
              else
              {
              Console.WriteLine($"{p1} matches");
              }
              }
              }


              Output:




              aaaa999999 matches

              aaaa9999999 matches

              aaaa99999999 doesn't match

              aaa999999 doesn't match




              Try it as DotNetFiddle






              share|improve this answer

































                3














                Your conditions give:





                1. The first four characters must be alphanumeric: [A-Za-zd]{4}


                2. Followed by 6 or 7 numeric values: d{6,7}


                Put it together and anchor it:



                ^[A-Za-zd]{4}d{6,7}z


                Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.






                share|improve this answer































                  1














                  Try the following pattern:



                  @"^[A-za-zd]{4}d{6,7}$"





                  share|improve this answer























                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8764827%2fc-sharp-regex-validation-rule-using-regex-match%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    5 Answers
                    5






                    active

                    oldest

                    votes








                    5 Answers
                    5






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    34














                    The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:



                    var regex = @"^w{4}d{6,7}$";


                    See: Regular Expression Language - Quick Reference





                    The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.



                    var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

                    if (!match.Success)
                    {
                    // does not match
                    }





                    share|improve this answer






























                      34














                      The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:



                      var regex = @"^w{4}d{6,7}$";


                      See: Regular Expression Language - Quick Reference





                      The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.



                      var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

                      if (!match.Success)
                      {
                      // does not match
                      }





                      share|improve this answer




























                        34












                        34








                        34







                        The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:



                        var regex = @"^w{4}d{6,7}$";


                        See: Regular Expression Language - Quick Reference





                        The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.



                        var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

                        if (!match.Success)
                        {
                        // does not match
                        }





                        share|improve this answer















                        The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:



                        var regex = @"^w{4}d{6,7}$";


                        See: Regular Expression Language - Quick Reference





                        The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.



                        var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);

                        if (!match.Success)
                        {
                        // does not match
                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Nov 21 '16 at 0:39









                        SteveCav

                        5,6303851




                        5,6303851










                        answered Jan 6 '12 at 21:42









                        dtbdtb

                        171k26344402




                        171k26344402

























                            5














                            The following code demonstrates the regex usage:



                                    var cc1 = "FOOBAR"; // should fail.
                            var cc2 = "AAAA1111111"; // should succeed
                            var r = new Regex(@"^[0-9a-zA-Z]{4}d{6,7}$");
                            if (!r.IsMatch(cc2))
                            {
                            Console.WriteLine("cc2 doesn't match");
                            }
                            if (!r.IsMatch(cc1))
                            {
                            Console.WriteLine("cc1 doesn't match");
                            }


                            The output will be cc1 doesn't match.






                            share|improve this answer




























                              5














                              The following code demonstrates the regex usage:



                                      var cc1 = "FOOBAR"; // should fail.
                              var cc2 = "AAAA1111111"; // should succeed
                              var r = new Regex(@"^[0-9a-zA-Z]{4}d{6,7}$");
                              if (!r.IsMatch(cc2))
                              {
                              Console.WriteLine("cc2 doesn't match");
                              }
                              if (!r.IsMatch(cc1))
                              {
                              Console.WriteLine("cc1 doesn't match");
                              }


                              The output will be cc1 doesn't match.






                              share|improve this answer


























                                5












                                5








                                5







                                The following code demonstrates the regex usage:



                                        var cc1 = "FOOBAR"; // should fail.
                                var cc2 = "AAAA1111111"; // should succeed
                                var r = new Regex(@"^[0-9a-zA-Z]{4}d{6,7}$");
                                if (!r.IsMatch(cc2))
                                {
                                Console.WriteLine("cc2 doesn't match");
                                }
                                if (!r.IsMatch(cc1))
                                {
                                Console.WriteLine("cc1 doesn't match");
                                }


                                The output will be cc1 doesn't match.






                                share|improve this answer













                                The following code demonstrates the regex usage:



                                        var cc1 = "FOOBAR"; // should fail.
                                var cc2 = "AAAA1111111"; // should succeed
                                var r = new Regex(@"^[0-9a-zA-Z]{4}d{6,7}$");
                                if (!r.IsMatch(cc2))
                                {
                                Console.WriteLine("cc2 doesn't match");
                                }
                                if (!r.IsMatch(cc1))
                                {
                                Console.WriteLine("cc1 doesn't match");
                                }


                                The output will be cc1 doesn't match.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Jan 6 '12 at 21:47









                                SmiSmi

                                10.2k74255




                                10.2k74255























                                    4














                                    The following code is using a regular expression and checks 4 different patterns to test it, see output below:



                                    using System;
                                    using System.Text.RegularExpressions;
                                    public class Program
                                    {
                                    public static void Main()
                                    {
                                    var p1 = "aaaa999999";
                                    CheckMatch(p1);
                                    p1 = "aaaa9999999";
                                    CheckMatch(p1);
                                    p1 = "aaaa99999999";
                                    CheckMatch(p1);
                                    p1 = "aaa999999";
                                    CheckMatch(p1);
                                    }

                                    public static void CheckMatch(string p1)
                                    {
                                    var reg = new Regex(@"^w{4}d{6,7}$");
                                    if (!reg.IsMatch(p1))
                                    {
                                    Console.WriteLine($"{p1} doesn't match");
                                    }
                                    else
                                    {
                                    Console.WriteLine($"{p1} matches");
                                    }
                                    }
                                    }


                                    Output:




                                    aaaa999999 matches

                                    aaaa9999999 matches

                                    aaaa99999999 doesn't match

                                    aaa999999 doesn't match




                                    Try it as DotNetFiddle






                                    share|improve this answer






























                                      4














                                      The following code is using a regular expression and checks 4 different patterns to test it, see output below:



                                      using System;
                                      using System.Text.RegularExpressions;
                                      public class Program
                                      {
                                      public static void Main()
                                      {
                                      var p1 = "aaaa999999";
                                      CheckMatch(p1);
                                      p1 = "aaaa9999999";
                                      CheckMatch(p1);
                                      p1 = "aaaa99999999";
                                      CheckMatch(p1);
                                      p1 = "aaa999999";
                                      CheckMatch(p1);
                                      }

                                      public static void CheckMatch(string p1)
                                      {
                                      var reg = new Regex(@"^w{4}d{6,7}$");
                                      if (!reg.IsMatch(p1))
                                      {
                                      Console.WriteLine($"{p1} doesn't match");
                                      }
                                      else
                                      {
                                      Console.WriteLine($"{p1} matches");
                                      }
                                      }
                                      }


                                      Output:




                                      aaaa999999 matches

                                      aaaa9999999 matches

                                      aaaa99999999 doesn't match

                                      aaa999999 doesn't match




                                      Try it as DotNetFiddle






                                      share|improve this answer




























                                        4












                                        4








                                        4







                                        The following code is using a regular expression and checks 4 different patterns to test it, see output below:



                                        using System;
                                        using System.Text.RegularExpressions;
                                        public class Program
                                        {
                                        public static void Main()
                                        {
                                        var p1 = "aaaa999999";
                                        CheckMatch(p1);
                                        p1 = "aaaa9999999";
                                        CheckMatch(p1);
                                        p1 = "aaaa99999999";
                                        CheckMatch(p1);
                                        p1 = "aaa999999";
                                        CheckMatch(p1);
                                        }

                                        public static void CheckMatch(string p1)
                                        {
                                        var reg = new Regex(@"^w{4}d{6,7}$");
                                        if (!reg.IsMatch(p1))
                                        {
                                        Console.WriteLine($"{p1} doesn't match");
                                        }
                                        else
                                        {
                                        Console.WriteLine($"{p1} matches");
                                        }
                                        }
                                        }


                                        Output:




                                        aaaa999999 matches

                                        aaaa9999999 matches

                                        aaaa99999999 doesn't match

                                        aaa999999 doesn't match




                                        Try it as DotNetFiddle






                                        share|improve this answer















                                        The following code is using a regular expression and checks 4 different patterns to test it, see output below:



                                        using System;
                                        using System.Text.RegularExpressions;
                                        public class Program
                                        {
                                        public static void Main()
                                        {
                                        var p1 = "aaaa999999";
                                        CheckMatch(p1);
                                        p1 = "aaaa9999999";
                                        CheckMatch(p1);
                                        p1 = "aaaa99999999";
                                        CheckMatch(p1);
                                        p1 = "aaa999999";
                                        CheckMatch(p1);
                                        }

                                        public static void CheckMatch(string p1)
                                        {
                                        var reg = new Regex(@"^w{4}d{6,7}$");
                                        if (!reg.IsMatch(p1))
                                        {
                                        Console.WriteLine($"{p1} doesn't match");
                                        }
                                        else
                                        {
                                        Console.WriteLine($"{p1} matches");
                                        }
                                        }
                                        }


                                        Output:




                                        aaaa999999 matches

                                        aaaa9999999 matches

                                        aaaa99999999 doesn't match

                                        aaa999999 doesn't match




                                        Try it as DotNetFiddle







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jun 12 '18 at 13:43









                                        Matt

                                        15.3k766109




                                        15.3k766109










                                        answered Jun 12 '18 at 13:11









                                        kirti kant pareekkirti kant pareek

                                        473




                                        473























                                            3














                                            Your conditions give:





                                            1. The first four characters must be alphanumeric: [A-Za-zd]{4}


                                            2. Followed by 6 or 7 numeric values: d{6,7}


                                            Put it together and anchor it:



                                            ^[A-Za-zd]{4}d{6,7}z


                                            Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.






                                            share|improve this answer




























                                              3














                                              Your conditions give:





                                              1. The first four characters must be alphanumeric: [A-Za-zd]{4}


                                              2. Followed by 6 or 7 numeric values: d{6,7}


                                              Put it together and anchor it:



                                              ^[A-Za-zd]{4}d{6,7}z


                                              Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.






                                              share|improve this answer


























                                                3












                                                3








                                                3







                                                Your conditions give:





                                                1. The first four characters must be alphanumeric: [A-Za-zd]{4}


                                                2. Followed by 6 or 7 numeric values: d{6,7}


                                                Put it together and anchor it:



                                                ^[A-Za-zd]{4}d{6,7}z


                                                Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.






                                                share|improve this answer













                                                Your conditions give:





                                                1. The first four characters must be alphanumeric: [A-Za-zd]{4}


                                                2. Followed by 6 or 7 numeric values: d{6,7}


                                                Put it together and anchor it:



                                                ^[A-Za-zd]{4}d{6,7}z


                                                Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jan 6 '12 at 21:43









                                                QtaxQtax

                                                27.4k554100




                                                27.4k554100























                                                    1














                                                    Try the following pattern:



                                                    @"^[A-za-zd]{4}d{6,7}$"





                                                    share|improve this answer




























                                                      1














                                                      Try the following pattern:



                                                      @"^[A-za-zd]{4}d{6,7}$"





                                                      share|improve this answer


























                                                        1












                                                        1








                                                        1







                                                        Try the following pattern:



                                                        @"^[A-za-zd]{4}d{6,7}$"





                                                        share|improve this answer













                                                        Try the following pattern:



                                                        @"^[A-za-zd]{4}d{6,7}$"






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jan 6 '12 at 21:46









                                                        BernardBernard

                                                        7,37723030




                                                        7,37723030






























                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8764827%2fc-sharp-regex-validation-rule-using-regex-match%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            MongoDB - Not Authorized To Execute Command

                                                            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                                            Npm cannot find a required file even through it is in the searched directory