No periods at the beginning or end of an expression?

I want to allow alphanumeric characters and periods; however, a phrase cannot contain more than two or more periods in a line, it cannot begin or end with a period, and spaces are not allowed.

I am using PHP and Javascript.

I still have /^(?!.*\.{2})[a-zA-Z0-9.]+$/

This works to resolve alphanumeric characters and periods, while at the same time negating spaces and consecutive periods, but I'm still not sure how to check the start and / or end periods. How can i do this? and is there an even better way to do what I already have?

+4
source share
3 answers

here is a possible way

 /^(?!\.)((?:[az\d]|(?<!\.)\.)+)(?<!\.)$/i 

for further explanation and tests see here: http://www.regex101.com/r/rZ6yH4

edit: according to tyler's solution, here is his way, shortened and shortened to letters and numbers

 /^(?:[az\d]+(?:\.(?!$))?)+$/i 

( http://www.regex101.com/r/dL5aG0 )

+1
source

It almost always helps draw a state machine to conceptualize what your regular expression should look like.

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

The beginning would be:

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

but it must be thoroughly tested.

0
source

All Articles