14

I have a Regex to allow alphanumeric, underscore and dots but not consecutive dots:

^(?!.*?[.]{2})[a-zA-Z0-9_.]+$

I also need to now allow dots in the first and last character of the string.

How can I do this?

3 Answers 3

37

You can use it like this with additional lookaheads:

^(?!\.)(?!.*\.$)(?!.*\.\.)[a-zA-Z0-9_.]+$
  • (?!\.) - don't allow . at start
  • (?!.*\.\.) - don't allow 2 consecutive dots
  • (?!.*\.$) - don't allow . at end
Sign up to request clarification or add additional context in comments.

9 Comments

just want to point out that this can be written shorter like ^(?!\.)(?!.*\.$)(?!.*?\.\.)[\w.]+$
Yes indeed \w is shortcut for [[a-zA-Z0-9_] in many regex flavors but not supported in awk, sed etc.
And to disallow string starting with a digit, I added (?!\d) to make the regex: ^(?!\d)(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9_.]+$. Thanks for the breakdown of each regex portion. :)
use preg_match("/^(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9_.]+$/", $number, $m); and them print $m[0]
I am using this regex in android but still allowing dot at the start
|
3

Re-write the regex as

^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*$

or (in case your regex flavor is ECMAScript compliant where \w = [a-zA-Z0-9_]):

^\w+(?:\.\w+)*$

See the regex demo

Details:

  • ^ - start of string
  • [a-zA-Z0-9_]+ - 1 or more word chars
  • (?:\.[a-zA-Z0-9_]+)* - zero or more sequences of:
    • \. - a dot
    • [a-zA-Z0-9_]+ - 1 or more word chars
  • $ - end of string

Comments

0

You can try this:

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

This will not allow any consecutive dots in the string and will also allow dot as first and last character

Tried here

Comments

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.