简体   繁体   English

检查字符串是否匹配正则表达式的前 n 个字符

[英]check if string matches first n characters of regex

I have a python site built in Django where a user will be uploading files that they may or may not have permission to add.我在 Django 中构建了一个 python 站点,用户将在其中上传他们可能有权或可能没有权限添加的文件。 The permissions are created through a series of regex patterns (there is over 1000).权限是通过一系列正则表达式模式创建的(超过 1000 个)。 At one point in my site I have a place for the user to view their permissions (using a search filter and a list).在我的站点中,我有一个地方供用户查看他们的权限(使用搜索过滤器和列表)。 However what I want to do is if the user types in a string and the string matches any part of each regular expression.但是我想要做的是如果用户输入一个字符串并且该字符串匹配每个正则表达式的任何部分。 I want it in the list.我想要它在列表中。

Right now I have if(filter.match(pattern)) { //add pattern to list } I have also tried searching instead of matching.现在我有if(filter.match(pattern)) { //add pattern to list }我也尝试过搜索而不是匹配。

An example of what I am looking for:我正在寻找的一个例子:

If I have a list of regex patterns:如果我有一个正则表达式模式列表:

^(12345678)\.(txt)$
^(qwertyuiop)\.(txt)$
^(qwerty)\.(txt)$
^(23456)\.(txt)$

if the user were to enter qwert the list would show ^(qwertyuiop)\.(txt)$ and ^(qwerty)\.(txt)$ , whereas if the user entered qwertyu the list would only show ^(qwertyuiop)\.(txt)$ .如果用户输入 qwert,列表将显示^(qwertyuiop)\.(txt)$^(qwerty)\.(txt)$ ,而如果用户输入 qwertyu,则列表将仅显示^(qwertyuiop)\.(txt)$ Similarly if the user entered 234 the list would show ^(12345678)\.(txt)$ and ^(23456)\.(txt)$ but if the user entered 1 the list would only show ^(12345678)\.(txt)$ .同样,如果用户输入 234,则列表将显示^(12345678)\.(txt)$^(23456)\.(txt)$但如果用户输入 1,则列表将仅显示^(12345678)\.(txt)$

Is it possible to accomplish this?有可能做到这一点吗? If so how would I manage it?如果是这样,我将如何管理它?

Thanks for the Help!谢谢您的帮助!

re.search should work for this. re.search应该为此工作。 By the sound of it you're not too picky with users entering arbitrary strings that could crash your server.听上去你对用户输入可能导致服务器崩溃的任意字符串不太挑剔。 If so you could just do this.如果是这样,你可以这样做。

import re

patterns = [
    r"^(12345678)\.(txt)$",
    r"^(qwertyuiop)\.(txt)$",
    r"^(qwerty)\.(txt)$",
    r"^(23456)\.(txt)$",
]

filter = re.compile("qwert")
filtered_patterns = [p for p in patterns if filter.search(p)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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