1

I need help building a regular expression for preg_match according these rules:

  1. first and last char- letter/digit only.
  2. empty space not allowed
  3. char can be only - letter/digit/'-'/'_'/'.'

Legal examples:

  1. b.t612_rt
  2. rut-be
  3. rut7565

Not legal example:

  1. .btr78; btr78- (first/last allowed chars)
  2. start end; star t end; (any empty space)
  3. tr$be; tr*rt; tr/tr ... (not allowed chars)

Edit: I remove 4 rule with neigbor chars '_'\'-'\'.'

please help me.

Thanks

2
  • 4
    Why don't you try writing one yourself, and we can help you if it doesn't work as intended? You'll never learn anything if you ask others to do all your work for you without even attempting it first. Commented Feb 2, 2011 at 14:36
  • Open-source alternatives to RegexBuddy lists a few nice tools to help with constructing a regular expression. Commented Feb 2, 2011 at 14:45

4 Answers 4

3

Try this regular expression:

^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$

This matches any sequence that starts with at least one letter or digit (^[A-Za-z0-9]+) that may be followed by zero or more sequences of one of -, _, or . ([-_.]) that must be followed by at least one letter or digit ([A-Za-z0-9]+).

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for simplest solution without a bunch of look-ahead stuff.
@dani: Then replace [-_.] by [-_.]+.
2

Try this:

^[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]$

In PHP:

if (preg_match(
    '%^               # start of string
    [\p{L}\p{N}]      # letter or digit
    [\p{L}\p{N}_.-]*  # any number of letters/digits/-_.
    [\p{L}\p{N}]      # letter or digit
    $                 # end of the string.
    %xu', 
    $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

Minimum string length: Two characters.

Comments

1

This seems to work fine for provided examples: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';

Comments

1

Well, for each of your rules:

  1. First and last letter/digit:

    ^[a-z0-9]
    

    and

    [a-z0-9]$
    
  2. empty space not allowed (nothing is needed, since we're doing a positive match and don't allow any whitespace anywhere):

  3. Only letters/digits/-/_/.

    [a-z0-9_.-]*
    
  4. No neighboring symbols:

    (?!.*[_.-][_.-])
    

So, all together:

/^[a-z0-9](?!.*[_.-][_.-])[a-z0-9_.-]*[a-z0-9]$/i

But with all regexes, there are multiple solutions, so try it out...

Edit: for your edit:

/^[a-z0-9][a-z0-9_.-]*[a-z0-9]$/i

You just remove the section for the rule you want to change/remote. it's that easy...

1 Comment

@meagar: fixed, I didn't add the any character match to the forward assertion. It should work now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.