正则表达式匹配任何字符还是不匹配?

2024-05-16 11:12:02 发布

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

我有以下两条弦

line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore

line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore

我试着抓住这两部分

"GET /file/ HTTP/1.1" 302
"" 400

基本上是介于两个“”之间的任何字符,或介于“”之间的任何字符。到目前为止我已经试过了

regex_example = re.search("\".+?\" [0-9]{3}", line1)
print regex_example.group()

这适用于第1行,但第2行有错误。这是由于“.”匹配任何字符,但如果不存在字符,则给出错误。

它有没有办法在两个“”之间匹配任何字符或不匹配任何字符?


Tags: rehttpsearchgetexample错误random字符
3条回答

使用.*?而不是.+?

+表示“1或更多”

*表示“0或更多”

Regex101 Demo

如果需要更有效的正则表达式,请使用反字符类[^"],而不是惰性量词?。您还应该对数字使用原始字符串标志r\d

r'"[^"]*" \d{3}'

更简单的答案。

    import re
    line1= '[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore'
    line2='[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore'

    x=re.search('\](.+)random',line1).group(1)

    y= re.search('\](.+)random', line2).group(1)

    print(x + "\n"+y)

您将得到以下输出

     "GET /file/ HTTP/1.1" 302 
     "" 400

您可以使用:

import re

lines = ['[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore', '[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore']

rx = re.compile(r'''
        "[^"]*" # ", followed by anything not a " and a "
        \       # a space
        \d+     # at least one digit
        ''', re.VERBOSE)

matches = [m.group(0) \
            for line in lines \
            for m in rx.finditer(line)]

print(matches)
# ['"GET /file/ HTTP/1.1" 302', '"" 400']


a demo on ideone.com

相关问题 更多 >