Python regex匹配API路径

2024-09-27 00:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个正则表达式匹配api路径与以下规则

  1. 路径以“/”开头,但可以有多个“/”
  2. “/”后面必须跟一个以小写开头的单词,但以后可以是大写

    x = ["/word/worD/sdfsfsd","/fsdfsdf","/","/{sfsdf",'/','/_','/{','/{"type":"tnt"}',"/allGear{Exe","/Grear"]
    
    import re
    
    pattern = re.compile("(/[a-z][a-zA-Z]+)+")
    
    for y in x:
         print (pattern.match(y))
    

因此在本例中,只有前两个元素必须生成匹配。你知道吗


Tags: 路径reapi规则type单词wordpattern
2条回答

使用以下方法:

import re
x = ["/word/worD/sdfsfsd","/fsdfsdf","/","/{sfsdf",'/','/_','/{','/{"type":"tnt"}',"/allGear{Exe","/Grear"]
result = [p for p in x if re.match(r'^(\/[a-z][a-zA-z]+)+$', p)]

print(result)

输出:

['/word/worD/sdfsfsd', '/fsdfsdf']

我想这应该适合你。但是,正如在评论中所说的,我认为根据你的描述/allGear{Exe也应该包括在内。我给出的代码也返回了这个结果

 x = ["/word/worD/sdfsfsd","/fsdfsdf","/","/{sfsdf",'/','/_','/{','/{"type":"tnt"}',"/allGear{Exe","/Grear"]


import re

for i in x:
    pattern = re.search("""\/[a-z][a-zA-Z]+""", i, re.S)
#If you don't want the /allGear, change the regex to """\/[a-z][a-zA-Z]+$""";
    if(pattern is not None):
        print i

相关问题 更多 >

    热门问题