簡體   English   中英

Python:使用re.match檢查字符串

[英]Python: check string using re.match

我需要寫func來檢查str。 如果應符合以下條件:

1)str應該以字母開頭- ^[a-zA-Z]

2)str可以包含字母,數字,一個. 還有一個-

3)str應該以字母或數字結尾

4)str的長度應為1到50

def check_login(str):
    flag = False
    if match(r'^[a-zA-Z][a-zA-Z0-9.-]{1,50}[a-zA-Z0-9]$', str):
        flag = True
    return flag

但是,這應該意味着它以字母開頭, [a-zA-Z0-9.-]的長度大於0且小於51,並且以[a-zA-Z0-9]結尾。 如何限制的數量. -並且將長度限制寫入所有表達式?

我的意思a --應該返回true, qwe123也返回true。

我該如何解決?

您將需要提前:

^                              # start of string
    (?=^[^.]*\.?[^.]*$)        # not a dot, 0+ times, a dot eventually, not a dot
    (?=^[^-]*-?[^-]*$)         # same with dash
    (?=.*[A-Za-z0-9]$)         # [A-Za-z0-9] in the end
    [A-Za-z][-.A-Za-z0-9]{,49} 
$

參見regex101.com上的演示


Python可能是:

 import re rx = re.compile(r''' ^ # start of string (?=^[^.]*\\.?[^.]*$) # not a dot, 0+ times, a dot eventually, not a dot (?=^[^-]*-?[^-]*$) # same with dash (?=.*[A-Za-z0-9]$) # [A-Za-z0-9] in the end [A-Za-z][-.A-Za-z0-9]{,49} $ ''', re.VERBOSE) strings = ['qwe123', 'qwe-123', 'qwe.123', 'qwe-.-123', '123-'] def check_login(string): if rx.search(string): return True return False for string in strings: print("String: {}, Result: {}".format(string, check_login(string))) 

這樣產生:

 String: qwe123, Result: True String: qwe-123, Result: True String: qwe.123, Result: True String: qwe-.-123, Result: False String: 123-, Result: False 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM