正则表达式匹配任何字符或空字符?

17

我有以下两个字符串:

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

基本上是两个引号之间的任何字符或者没有字符。到目前为止我尝试过这个:

Basically any character in between the two "" or nothing in between "". So far I've tried this;

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

这个方法可以处理line1,但会因为'.'匹配任何字符且没有字符存在时报错而无法处理line2。

是否有办法使它在两个引号之间匹配任何字符或不匹配任何字符?


1
使用 r'"[^"]*" [0-9]{3}' - anubhava
5个回答

40

使用.*?替代.+?

+表示"1个或更多"

*表示"0个或更多"

Regex101演示

如果您想要一个更有效的正则表达式,请使用否定字符类[^"]而不是懒惰量词?。您还应该使用原始字符串标志r\d来表示数字。

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

1

您可以使用:

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']

请看ideone.com上的演示

0
更简单的答案。
    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

0

试试这个... 使用'findall'代替'search'可能会更好地控制您想要如何处理输出。

import re

output = []

logs = '[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'

regex = r'"(.*?)"\s(\d{3})'

value = re.findall(regex, logs)
output.append(value)

print(output)

0

另一个选项是:

import re
re.sub('\[.*\] ', '', your_string)

这会将方括号 [] 中的任何字符组合替换为一个空字符串 "",并在 your_string 中返回结果。

例如:

for your_string in [line1, line2]:
    print(re.sub('\[.*\] ', '', your_string))

输出

>>>"GET /file/ HTTP/1.1" 302 random stuff ignore'
>>>"" 400 random stuff ignore'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接