Python 正則表示式限定文字長度
阿新 • • 發佈:2019-02-07
Regex Expression
# Limit the string length between 1 and 10 letters (a-z, A-Z) ^[a-zA-Z]{1,10}$ eg. match: abceddddd no match: aaaaaaaaaaa # Limit the lenght of an arbitrayry pattern ^(?=[\S\s]{1,10}$)[\S\s]* eg. match: a-$%^&**u1 no match: a-$%^&**u1aa # Limit the length of nonwhitespace characters (whitespace may exist among nonwhitespace characters) ^\s*(?:\S\s*){1,10}$ eg. match: 2008 ddddd d no match: 2008 ddddd dd # Limit the number of words ^\W*(?:\w+\b\W*){1,10}$ eg. match: abd dd22dd ddd ddd dd dd dd d1d _d dd no match: abd dd22dd ddd ddd dd dd dd d1d _d dd dd
CODE:
import re
if re.match(r"^\W*(?:\w+\b\W*){1,10}$", subject):
# Successful match at the start of the string
else:
# Match attempt failed