Home > front end >  Regular Expression to match Digital Ocean Bucket Name Rule
Regular Expression to match Digital Ocean Bucket Name Rule

Time:10-25

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

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.

CodePudding user response:

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

  • Related