Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Match 15 Characters, Single Spaces, Alpha-Numeric

Tags:

c#

regex

I need to match a string under the following conditions using Regex in C#:

  1. Entire string can only be alphanumeric (including spaces).
  2. Must be a maximum of 15 characters or less (including spaces).
  3. First & last characters can only be a letter.
  4. A single space can appear multiple times in anywhere but the first and last characters of the string. (Multiple spaces together should not be allowed).
  5. Capitalization should be ignored.
  6. Should match the WHOLE word(s).

If any one of these preconditions are broken, a match should not follow.

Here is what i currently have:

^\b([A-z]{1})(([A-z0-9 ])*([A-z]{1}))?\b$

And here are some test strings that should match:

  • Stack OverFlow
  • Iamthe greatest
  • A
  • superman23s
  • One Two Three

And some that shouldn't match (note the spaces):

  • Stack [double_space] Overflow Rocks
  • 23Hello
  • ThisIsOver15CharactersLong
  • Hello23
  • [space_here]hey

etc.

Any suggestions would be much appreciated.

like image 855
user1684699 Avatar asked Nov 30 '12 10:11

user1684699


2 Answers

You should use lookaheads

                                                               |->matches if all the lookaheads are true
                                                               --
^(?=[a-zA-Z]([a-zA-Z\d\s]+[a-zA-Z])?$)(?=.{1,15}$)(?!.*\s{2,}).*$
-------------------------------------- ----------  ----------
                 |                       |           |->checks if there are no two or more space occuring
                 |                       |->checks if the string is between 1 to 15 chars
                 |->checks if the string starts with alphabet followed by 1 to many requireds chars and that ends with a char that is not space

you can try it here

like image 148
Anirudha Avatar answered Sep 20 '22 12:09

Anirudha


Try this regex: -

"^([a-zA-Z]([ ](?=[a-zA-Z0-9])|[a-zA-Z0-9]){0,13}[a-zA-Z])$"

Explanation : -

[a-zA-Z]    // Match first character letter

(                         // Capture group
    [ ](?=[a-zA-Z0-9])    // Match either a `space followed by non-whitespace` (Avoid double space, but accept single whitespace)
            |             // or
    [a-zA-Z0-9]           // just `non-whitespace` characters

){0,13}                  // from `0 to 13` character in length

[a-zA-Z]     // Match last character letter

Update : -

To handle single characters, you can make the pattern after 1st character optional as nicely pointed by @Rawling in comments: -

"^([a-zA-Z](([ ](?=[a-zA-Z0-9])|[a-zA-Z0-9]){0,13}[a-zA-Z])?)$"
         ^^^                                            ^^^
     use a capture group                           make it optional
like image 41
Rohit Jain Avatar answered Sep 18 '22 12:09

Rohit Jain