我嘗試撰寫正則運算式來驗證具有這樣規則的 Digital Ocean Bucket Name
存盤桶名稱只能由小寫字母、數字、點 (.) 和連字符 (-) 組成。存盤桶名稱必須以字母或數字開頭和結尾。
我不擅長正則運算式。我只能解決最后一條規則“存盤桶名稱必須以字母或數字開頭和結尾。使用 pattern "^[a-z0-9].*[a-z0-9]$"
,但規則僅包含小寫字母、數字、點和連字符
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
但是上面的運算式,沒有任何匹配。但是,它應該匹配string_one, string_five, and string_six
你能幫忙嗎?謝謝。
uj5u.com熱心網友回復:
如果要匹配字串 1,5 和 6,并且還允許在其間留一個空格并a-z0-9
匹配單個字符:
^[a-z0-9][a-z0-9. -]*[a-z0-9]$
正則運算式演示| Python 演示
請注意,這至少匹配 2 個字符,并且當它位于字符類的末尾時,您不必轉義點和連字符。
還允許單個字符:
^[a-z0-9](?:[a-z0-9. -]*[a-z0-9])?$
正則運算式演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/519980.html