Some help with a regex needed.

Discussion in 'Programming' started by x0x, Oct 27, 2009.

  1. #1
    I am helpless when it comes to regex.


    Here is what I need:


    1. Only letters (any case) or numbers allowed. Can be combined or alone.

    2. Special characters allowed: "-" and " ".
    Between quotes, no commas. The second one is space. Two of both can be used, but not consecutively e.g "m--e" would not return false. Also, they can't be combined and used consecutively ("me -" with a space before the dash.) - would also return false. Also, these special characters can't be used alone and they can't be used in the beginning or at the end of the word/number or both.

    Some examples:

    Bad: "-name-", " name", "-", "name ", "6-6-"
    Good: "na-me", "got no name", "1-1", "my-name 11", "A-a-a B b"


    What I have right now:


    /^[a-z0-9](\s?[a-z0-9\.\-]*|[a-z0-9\.\-]*\s|[a-z0-9\.\-]*\s[a-z0-9\.\-_]*)$/i'
    PHP:
    But I know it's far from what I need...

    Any help would highly be appreciated!
     
    x0x, Oct 27, 2009 IP
  2. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #2
    I think this is what you are looking for:
    
    /(^[a-z0-9]$|^[a-z0-9]([\s\-]{1}|[a-z0-9]+)*[a-z0-9]$)/i
    
    Code (markup):
    The first part handles the special case where you only have one character and the the second just says it begins with an alphanum and ends with an alphanum, The middle part says it is either exactly one whitespace or - or one or more alphanums and then repeats that pattern 0 or more times.
     
    superdav42, Oct 28, 2009 IP