Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular Expression to match Digital Ocean Bucket Name Rule

I tried to write the regular expression to validate the Digital Ocean Bucket Name which has rule like this

Bucket names can consist only of lowercase letters, numbers, dots (.),
and hyphens (-). Bucket names must begin and end with a letter or
number.

I’m poor at regular expression. I could only solve the last rule "Bucket names must begin and end with a letter or number. With pattern "^[a-z0-9].*[a-z0-9]$", but rule that consist of only lower case letter, number, dots, and hypnens

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import re

# Start and end with letter or number
# pattern = "^[a-z0-9].*[a-z0-9]$"

# Start and end with letter or number, and consist only letter,
# number, dot, and hyphens
pattern = "^[a-z0-9]+[a-z0-9\.\-]+[a-z0-9]$"


string_one = "hello world"
string_two = "hello ^ world 2"
string_three = "hello world *"
string_four = "Hello - World 9"
string_five = "hello - world 9"
string_six = "2hello.world 9"


if re.search(pattern, string_one):
    print "matched with string one: ",string_one

if re.search(pattern, string_two):
    print "matched with string two: ",string_two

if re.search(pattern, string_three):
    print "matched with string three: ",string_three

if re.search(pattern, string_four):
    print "matched with string four: ",string_four

But the above expressions, nothing is matched. However, it should match string_one, string_five, and string_six Could you please help ? Thanks.

>Solution :

If you want to match string 1,5 and 6 and also allow a space in between and a single character a-z0-9 to match:

^[a-z0-9][a-z0-9. -]*[a-z0-9]$

Regex demo | Python demo

Note that this matches at least 2 characters, and you don’t have to escape the dot and the hyphen when it is at the end of the character class.

To also allow a single character:

^[a-z0-9](?:[a-z0-9. -]*[a-z0-9])?$

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading