简体   繁体   中英

Python3, re.match with list

I read this : https://stackoverflow.com/a/17090205/6426449

And I made a list that cannot be used on username in django.

list : FORBIDDEN_USERNAME_LIST = ['admin', 'master', 'owner']

So I made a code like this :

views.py

def username_choice(request):

    if request.method == "POST":
        username = request.POST['username']    
        for item in forbidden.FORBIDDEN_USERNAME_LIST:
            match = re.search("r'\b"+item+"\b'", username)
            if match:
                return JsonResponse({'result': item + 'banned username'})

But It seems that it does not work.

Maybe I think, match = re.search("r'\\b"+item+"\\b'", username) Here is problem.

How can I fix that?

You could simply use in :

forbidden = ['admin', 'master', 'owner']
username = request.POST['username']
match = [nm for nm in forbidden if nm in username]
if match:
    # part of the username is in the forbidden list.

Example in IPython:

In [1]: forbidden = ['admin', 'master', 'owner']

In [2]: username = 'owner123'

In [3]: match = [nm for nm in forbidden if nm in username]

In [4]: match
Out[4]: ['owner']
def username_choice(request):

    if request.method == "POST":
        username = request.POST['username']    
        for item in forbidden.FORBIDDEN_USERNAME_LIST:
          if re.search(r'\b'+str(item)+'\\b', username, re.I):
              return JsonResponse({'result': item + 'banned username'})

Just use this statement:

match = re.search(r'[%s]+' % item, username, re.I)

instead of this:

match = re.search("r'\b"+item+"\b'", username)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM